开发者

Using reactive to resubscribe each time another event occurs

I want to subscribe to an observable, but only run an action once until a different IObservable fires. Each time the other IObservable fires, I'd like to be resubscribed and run my action once. The following code should accomplish that:

Action<object> act = null;
act = _ => {
    DoThis();
    obj.Observable1.SkipUntil(obj.CompletedObservable).Take(1).Subscribe(act);
};
obj.Observable1.Take(1).Subscribe(act);

Is there a more proper way to do this wi开发者_运维知识库th the Rx framework? If not, how could I wrap this pattern into an extension?


It seems that you want something like this:

first  -----1------------2-------------3--4--------->
            |            |             |  |
second ---------A--B----------C-D-E-----------F---G->
                |             |               |
final  ---------A-------------C---------------F----- >

For this, a combination of SelectMany, Take, and TakeUntil should work. I would say:

var final = from f in first
            from s in second.Take(1).TakeUntil(first)
            select s;

The .Take(1) ensures that you only get the first item after the first (for 1, 2, and 4). The .TakeUntil(first) covers 3, so that F only gets passed once (to 4). If you have a nice name for this operation, it would be easy to wrap into a method taking the two observables as parameters.


I think I've got it:

obj
    .CompletedObservable
    .StartWith(/* value of suitable type for CompletedObservable */)
    .Select(x => obj.Observable1.Take(1))
    .Switch()
    .Subscribe(x => DoThis());


Have you tried the following:

obj.CompletedObservable
    .Select(_ => obj.Observable1.Next().First())
    .Subscribe(_ => DoThis());
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜