TomZ
TomZ

Reputation: 421

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 with the Rx framework? If not, how could I wrap this pattern into an extension?

Upvotes: 0

Views: 254

Answers (3)

Gideon Engelberth
Gideon Engelberth

Reputation: 6155

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.

Upvotes: 2

Enigmativity
Enigmativity

Reputation: 117175

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

Upvotes: 1

David Grenier
David Grenier

Reputation: 1110

Have you tried the following:

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

Upvotes: 0

Related Questions