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?
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With