How can I control which items are pushed through an observable a depending on the (boolean) values of another observable b?
I mean, items are in a are pushed only if last item emitted by b is true.
Observable sequence b should act like a pass filter.
OK, I think I have at least a solution
It can be done with a combination of WithLatestFrom and Where.
In my real code, I have this:
positionObs
.WithLatestFrom(isSeekingObs, (pos, isSeeking) => new { pos, isSeeking })
.Where(x => !x.isSeeking)
.Select(x => x.pos);
It essential combine the two most recent values and applies a filter on the "signaler".
Anyway, I'd like to know if there's a cleaner solution.
My preferred way to do this kind of thing is with a combination of Publish and Switch.
Here's how:
Subject<bool> subject_b = new();
IObservable<bool> observable_b = subject_b.AsObservable();
IObservable<long> observable_a = Observable.Interval(TimeSpan.FromSeconds(1.0));
IObservable<long> observable_c =
observable_a
.Publish(published_a =>
observable_b
.Select(value_b =>
value_b
? published_a
: Observable.Never<long>()))
.Switch();
IDisposable subscription = observable_c.Subscribe(Console.WriteLine);
Thread.Sleep(TimeSpan.FromSeconds(2.5));
subject_b.OnNext(true);
Thread.Sleep(TimeSpan.FromSeconds(3));
subject_b.OnNext(false);
Thread.Sleep(TimeSpan.FromSeconds(4));
subject_b.OnNext(true);
That gives:
2
3
4
9
10
11
12
13
14
...
I prefer Publish/Switch over WithLatestFrom as there are more variety of queries that the former handles that the latter doesn't.