Martijn Martijn - 3 months ago 9
C# Question

Stopping an Observable when a next is available

I have the following things:

IObservable<A> as_;
Func<A, IObservable<B>> getbs;


getbs
is a function that returns an infinte observable of
B
s.

I would like to get an
IObservable<B>
that "switches" to the next
IObservable<B>
as soon as the next
A
in as is "available".

Something like
as_.SelectMany(getbs)
won't work, because it will keep getting
B
s from the first
A
, as the sequence never naturally terminates.

Answer

SelectMany is like a Select followed by a Merge. You need to use Select with your function then Switch.

IObservable<int> a = Observable.Generate(0, _ => true, i => i + 1, i => i, _ => TimeSpan.FromSeconds(1));
Func<int, IObservable<string>> selector = i => Observable.Generate(1, _ => true, j => j + 1, j => $"{i} x {j}", _ => TimeSpan.FromMilliseconds(50));

a.Select(selector).Switch().Subscribe(s => Console.WriteLine(s));