任务功能提供无限IObservable并切换可观察 [英] Infinite IObservable from Task function and toggle observable

查看:106
本文介绍了任务功能提供无限IObservable并切换可观察的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两件事:返回 Task< TResult>的函数;查询 IObservable< bool>切换。我要创建的是 IObservable< TResult> ,当切换得出 true ,它会启动一个无限循环,每次都调用 query 并返回结果。然后,当切换得到 false 时,它应该停止无限循环。

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.

我确实读过如何使无限从任务循环,但我不知道如何切换。另外,它不能在无限循环中运行 query 并对其进行过滤。如果 toggle false ,则根本不应该调用查询。同样,如果 toggle 为假,那就太好了,如果 query 已经启动,则结果可观察值将不会返回。当 toggle 为假,但没有必要时,取消查询也可能是个好主意。

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.

推荐答案

我认为正是您想要的:

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

这篇关于任务功能提供无限IObservable并切换可观察的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆