fweigl
fweigl

Reputation: 22028

Switch observable on condition

I have two observables and I want to use the first one unless it doesn't give me what I want (in this case an empty list). If that's the case I wwant to switch to the second one.

fun test() {

    listSource1().switchMap {
        if (it.isEmpty()) listSource2() else listSource1()
    }

}

fun listSource1() = Observable.just(emptyList<String>())

fun listSource2() = Observable.just(listOf("hello"))

Is there a better way than this? it seems strange to map listSource1 to listSource1, is this the correct way to do it?

Upvotes: 1

Views: 464

Answers (1)

akarnokd
akarnokd

Reputation: 69997

FlatMap the first to see if the item is an empty list:

Observable<List<T>> source = ...

Observable<List<T>> fallbackSource = ...

source.flatMap(list -> {
    if (list.isEmpty()) {
        return fallbackSource;
    }
    return Observable.just(list);
});

Upvotes: 1

Related Questions