Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Equivalent of RxJS switchMap in ReactiveX/Rx.NET

In RxJS, there is a switchMap function. Is there an equivalent in ReactiveX/Rx.NET? I don't see one in the transforming documentation.

like image 701
wonderful world Avatar asked Mar 31 '17 11:03

wonderful world


People also ask

What is RxJS switchMap?

RxJS switchMap() operator is a transformation operator that applies a project function on each source value of an Observable, which is later merged in the output Observable, and the value given is the most recent projected Observable.

What is the name of the method you call on an Observable to apply operators?

Chaining Operators Most operators operate on an Observable and return an Observable. This allows you to apply these operators one after the other, in a chain. Each operator in the chain modifies the Observable that results from the operation of the previous operator.

When to use switch Map?

Use mergeMap if you simply want to flatten the data into one Observable, use switchMap if you need to flatten the data into one Observable but only need the latest value and use concatMap if you need to flatten the data into one Observable and the order is important to you.

Which operator allows us to execute a function each time an item is emitted on the source Observable?

The doOnEach operator modifies the Observable source so that it notifies an Observer for each item and establishes a callback that will be called each time an item is emitted. The doOnSubscribe operator registers an action which is called whenever an Observer subscribes to the resulting Observable.


2 Answers

There is no single SwitchMany in Rx.NET equivalent to switchMap in Rx.js. You need to use separate Select and Switch functions.

Observable.Interval(TimeSpan.FromMinutes(1))
    .Select(_ => Observable.Return(10))
    .Switch()

Documentation: https://msdn.microsoft.com/en-us/library/hh229197(v=vs.103).aspx

like image 67
MorleyDev Avatar answered Sep 20 '22 08:09

MorleyDev


From http://reactivex.io/documentation/operators/switch.html

Switch operator subscribes to an Observable that emits Observables. Each time it observes one of these emitted Observables, the Observable returned by Switch unsubscribes from the previously-emitted Observable begins emitting items from the latest Observable.

As MorleyDev pointed, the .NET implementation is https://docs.microsoft.com/en-us/previous-versions/dotnet/reactive-extensions/hh229197(v=vs.103), so the equivalent of RxJS switchMap in Rx.NET is a combination of Switch and Select operators:

// RxJS
observableOfObservables.pipe(
    switchMap(next => transform(next))
    ...
)

// RX.Net
observableOfObservables
    .Switch()
    .Select(next => transform(next))
    ...
like image 25
vimant Avatar answered Sep 19 '22 08:09

vimant