Infinite IObservable from Task function and toggle

2019-07-27 15:16发布

问题:

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();