Ernest Zamelczyk
Ernest Zamelczyk

Reputation: 2839

Opposite of switchMap operator in RxJava2

I have configuration Observable to which I'm subscribing and launching my own Observable but I'm having a problem with canceling the running Observable upon receiving configuration update.

I was thinking of something like switchMap operator but in reverse so when there's a new value from a source Observable we're unsubscribing from the mapped Observable and subscribing to a new one.

Like this:

configuration.
    reverseSwitchMap {
        createMyObservable(it.somethingFromConfiguration) // this observable get's recreated for each configuration update
    }.subscribe {
        // here I'm receiving values from myObservable
    }

Is there an operator which could help me solve this problem?

Upvotes: 0

Views: 84

Answers (2)

Petar Marijanovic
Petar Marijanovic

Reputation: 89

That's exactly what switchMap is for.

This should work:

fun startUpdates() {
    configuration.toObservable()
        .switchMap { configuration -> MyObservable(configuration) }                  
        .subscribe { //do something }
}

Upvotes: 1

Ernest Zamelczyk
Ernest Zamelczyk

Reputation: 2839

I think I'm overcomplicating this so for now the solution I created is this:

private val disposable: Disposable? = null

fun startUpdates() {
    configuration.toObservable()
        .forEach { configuration ->
            disposable?.dispose
            disposable = MyObservable(configuration)
                .subscribe { //do something }
        }
}

It suffices for now, though I'll leave the question open in case someone finds a better solution.

Upvotes: 0

Related Questions