Search code examples
rx-javarx-java2

RxJava - Pass variable


I have the following code which compiles fine:

public Publisher<Foo> test() {
  return someObservable
         .map(a -> someMethod(a, null))
         .toFlowable(BackpressureStrategy.BUFFER);
}

I would now like to call a method and pass in the results of it to use instead of the null value. My guess is to wrap the original code like so:

public Publisher<Foo> test() {
  return getSomeCollection()
         .map(myCollection -> 
           someObservable
           .map(a -> someMethod(a, myCollection))
         )
        .toFlowable(BackpressureStrategy.BUFFER);
}

However that gives me a type mismatch error 'Cannot convert from Single<Object> to Publisher<Foo>'

If I change the outer map to flatMap I get 'Cannot convert from Flowable<Foo> to SingleSource<? extends Object>'

What do I need to modify to make this compile?


Solution

  • Use flatMapPublisher instead of map

    return getSomeCollection()
                .flatMapPublisher(myCollection ->
                        someObservable
                                .map(a -> someMethod(a, myCollection))
                                .toFlowable(BackpressureStrategy.BUFFER)
                );