Buffer data from database cursor while keeping UI responsive

前端 未结 2 593
遥遥无期
遥遥无期 2021-01-23 16:59

I have a database catalog that is populated, and a cursor that can be used to retrieve objects. This catalog can obviously be very large, and what I\'d like to do is use

2条回答
  •  爱一瞬间的悲伤
    2021-01-23 17:11

    Your problem is here:

               while (status == DbStatus.OK)
                {
                    var dbObject= Db.Create(cursor);
                    obs.OnNext(dbObject);
    
                    status = cursor.MoveToNext();
                }
    

    That loop runs synchronously as soon as someone subscribes, in a blocking way. Since you're creating the subscription on the UI thread (at the time you call Connect), it will run the entire thing on the UI thread. Change it to:

    return Observable.Create(obs =>
    {
        Observable.Start(() => {
            var cursor = Database.Instance.GetAllObjects();
            var status = cursor.MoveToFirst();
    
            while (status == DbStatus.OK)
            {
                var dbObject= Db.Create(cursor);
                obs.OnNext(dbObject);
    
                status = cursor.MoveToNext();
            }
    
            obs.OnCompleted();
        }, RxApp.TaskPoolScheduler);
    
        return Disposable.Empty;
    });
    

提交回复
热议问题