Infinite IObservable from Task function and toggle observable

好久不见. 提交于 2020-01-05 04:06:08

问题


I have two things : Function that returns Task<TResult> query and IObservable<bool> toggle. What I want to create is IObservable<TResult> that when toggle gets true, it start an infinite loop where it calls query every time and returns it's result. Then, when toggle gets false, it should stop the infinite loop.

I did read how to make an infinite loop from task, but I cannot figure out how to toggle it on and off. Also, it cannot run the query in infinite loop and just filter it. It should not call the query at all if toggle is false. Also, it would be great if toggle gets false, then the resulting observable would not return if query was already started. It might also be good idea to cancel the query when toggle is false, but it is not necessary.

And I would like it to be automatically testable.


回答1:


I think does exactly what you want:

IObservable<TResult> query =
    toggle
        .Select(b => b
            ? Observable
                .Defer(() => Observable.FromAsync(() => SomeFunction()))
                .Repeat()
            : Observable
                .Never<TResult>())
        .Switch();


来源:https://stackoverflow.com/questions/39984486/infinite-iobservable-from-task-function-and-toggle-observable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!