I found a way to make it simpler instead of using two flatmap
and filter
val a = Observable.just(false)
val b = Observable.just(true)
val x = Observable.just(Unit)
x.flatMap { a }
.filter { !it }
.flatMap { b }
.filter { it }
.subscribe {
// a must be false and b must be true
}
I want to filter so subscribe only invoke when a is false and b is true, the code above is correct but I want to find a way to make it more simple; I try to use concat but I don't know why I can't use it...
There are multiple ways you can accomplish that. Choosing a simpler
solution is opinion-based and depends on how you want to handle items emitted by a
and b
. While the latter one might not be that apparent when testing Observable.just
s, when it comes to more sophisticated Observables
you could see the difference.
In your example b
is subscribed to only if a
has the correct value. Was that intended?
For me the cleaner solution would be to zip
them and compare the contents "together". But this expects items from both Observable
before possibly emitting an item.
Observable.zip(a, b, BiFunction { a, b -> Pair(a, b) })
.filter { !it.first && it.second }
.subscribe {
// a must be false and b must be true
}
Edit:
To give you an example of a different way of accomplishing this, here's an example without filter
:
Observable.zip(a.takeWhile { !it }, b.takeWhile { it }, BiFunction { _, _ -> Unit })
.subscribe {
// a must be false and b must be true
}
(remember that they all have different expectations on a
and b
)