user3390695
user3390695

Reputation: 53

RxJava Single: flatMap if false

I have a list of Boolean Singles that I want to convert to a Maybe in the following way:

Go through each emission from the list in order, if the upstream emission is false flatMapMaybe to a Maybe.never() but if the emission is true subscribe to the next Single in the list until the list is empty.

Here is what I have so far:

private void subscribeIfAllTrue(List<Single<Boolean>> singles) {

    if (singles.isEmpty()) {
        return;
    }
    Single.concat(blockingSingles)
            .flatMapMaybe(
                    (Function<Boolean, MaybeSource<Boolean>>) shouldProgress -> {
                        if (shouldProgress) {
                            // flatMap to next single in list.
                            // if last in list then Maybe.just(true)
                        } else {
                            Maybe.never();
                            // break from list
                        }
                    }
}

This obviously doesn't work since we are subscribing to all singles via concat but that is not the behavior I want. Wondering if there was an rx operator to basically break; and stop subscribing from list of subscriptions if one emission is false, also when last in last just return Maybe.just(true). Was looking

The main reason I dont want to subscribe to all singles is that the upstream boolean emission is performing a ui change that and if one is false dont want to trigger the ui change for the rest by just breaking.

Upvotes: 2

Views: 1170

Answers (1)

akarnokd
akarnokd

Reputation: 69997

Maybe use takeUntil (and perhaps, lastElement()) for the desired pattern.

Mayble<Boolean> m = Single.concat(blockingSingles)
    .takeUntil(bool -> !bool)
    .lastElement()

Upvotes: 2

Related Questions