Search code examples
javajava-8reactivexrx-java2

RxJava access item downstream


I have chained a few rx operators together to do multiple tasks. I need to access a field from an object that is in the parent stream, downstream.

ie. How can I access channel.uid downstream?

createThing(panel) // Observable<~>
    .flatMapSingle(
            channel -> {
        return createOrUpdateItem(channel);
    })
    .flatMapCompletable(
            item -> {
        return linkItemToChannel(item.name, /* need access to channel.uid here */ channel.uid);
    });

Solution

  • Use Observable.flatmap(Function mapper, BiFunction resultSelector) (or Flowable version). E.g.:

    createThing(panel) //I assume that this method returns Observable
        .flatMap(channel -> createOrUpdateItem(channel).toObservable(),
                (channel, item) -> linkItemToChannel(item.name, channel.uid).toObservable())
        .toCompletable();
    

    There is no similar overrided methods for flatMapSingle or flatMapCompletable, so you have to convert your Single and Completable to Observable (or Flowable). Or you can write your own operator ;)