Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RxJava - Any way to combine scan and flatMap?

Let's say I have a function that takes a String and a long and returns a Single<String>.

Single<String> stringAddition(String someString, long value) {
  return Single.just(someString + Long.toString(value));
}

Now I have this Observable...

Observable.interval(1, SECONDS)
  .scan("", (cumulativeString, item) -> {
    // Need to return the result of stringAddition(cummulativeString, item)
  });

I'm at a loss on how to do this. Scan needs me to return a String, but II would like to use the method that returns a Single<String>. To me it seems like I need something that can combine the behaviour of both scan and flatMap. Is there any RxJava2 wizardry that can help me?

like image 520
Chris Horner Avatar asked Jul 20 '17 07:07

Chris Horner


1 Answers

You can achieve it as follows. This can be somewhat shortened if stringAddition would have returned Observable

Observable<String> scanned = Observable.interval(1, TimeUnit.SECONDS)
            .scan(
                    Observable.just(""),
                    (cumulativeString, item) ->
                        cumulativeString
                          .flatMap(str -> stringAddition(str, item).toObservable())
            )
            .flatMap(it -> it);
like image 116
m.ostroverkhov Avatar answered Nov 16 '22 13:11

m.ostroverkhov