Hey there, tried searching for this, but wasn't ab...
# rx
n
Hey there, tried searching for this, but wasn't able to pull any results. What's the best way to take an Observable, FlatMapSingle to a Single Observable, but wait until we receive the result of the Single Observable, and decide to either complete or move onto the next one. For example:
Copy code
getSomeObservable().flatMapSingle { t -> performAPICallWithData(t) }
I don't want to
performAPICallWithData
until the first one has completed, and I want to use the result from
performAPICallWithData
to determine wether I should perform the next one or complete everything
a
Could you do something like:
Copy code
val observable = getSomeObservable().share()

observable.take(1).switchMap { t -> performApiCallWithData(t).flatMap { if (it.rightKindOfData) observable.skip(1) else Observable.empty() }
You don't really need
switchMap
there since that'll probably not compile because you're using a single. Could just be
flatMap
, doesn't make a difference in this case
n
Thanks for the feedback! I ended up going with something like this for now
Copy code
getSomeObservable().map { t ->
performApiCallWithData(t).blockingGet()
}.takeWhile {
 !it.rightKindOfData 
}.ignoreElements()
Seems to be working at the moment, although I'm open to alternative approaches. Does that make sense to you?
a
It does, though it's always best to work to avoid
blockingGet
since it defeats a bit part of the purpose. That being said if it works at this point I'd say it's fine.
n
It bugged me enough to spend more time on it, and I think the most elegant solution is using
concatMapSingleDelayError
which seems to work perfectly. it ends up like
Copy code
getSomeObservable().concatMapSingleDelayError { t ->
performApiCallWithData(t)
}.takeWhile {
 !it.rightKindOfData 
}.ignoreElements()
The documentation is
Copy code
Maps the upstream items into SingleSources and subscribes to them one after the other succeeds or fails, emits their success values and delays all errors till both this Observable and all inner SingleSources terminate.
which is exactly what I was looking for. The key term being
subscribes to them one after the other succeeds or fails
a
awesome!