10

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

wonderful world
  • 10,969
  • 20
  • 97
  • 194

3 Answers3

14

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

MorleyDev
  • 141
  • 1
  • 4
2

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://learn.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))
    ...
vimant
  • 21
  • 2
  • 1
    I don't think you have the order correct. The `Switch` happens on inner observables but you haven't got any until you call `Select`. The above answer also has them the other way round. – PhilT Dec 22 '19 at 11:11
-4

Edit

switch is the equivalent. http://reactivex.io/documentation/operators/switch.html

In short, switchMap and switch will cancel any previous streams whereas flatMap will not.

Tyler Jennings
  • 8,761
  • 2
  • 44
  • 39