使用 Observable 从数据库流式传输数据
假设有一个方法返回 IEnumerable<T>
,fe
private IEnumerable<T> GetData()
{
try
{
// return results from database
}
catch(Exception exception)
{
throw;
}
}
创建一个 Observable 并异步启动一个方法。SelectMany
扁平化集合,并通过 Buffer
每 200 个元素触发订阅。
int bufferSize = 200;
Observable
.Start(() => GetData())
.SelectMany(s => s)
.Buffer(bufferSize)
.ObserveOn(SynchronizationContext.Current)
.Subscribe(items =>
{
Console.WriteLine("Loaded {0} elements", items.Count);
// do something on the UI like incrementing a ProgressBar
},
() => Console.WriteLine("Completed loading"));