Observe that the answer that has more votes here is a little bit misleading. See the example below, my idea is to show some testing scenarios and show how the completable logic with the operator andThen
behaves.
private fun doThingAFail(): Completable {
print("Do thingA Called\n")
return Completable.fromCallable {
print("calling stream A\n")
throw(Exception("The excep"))
}
}
private fun doThingB(): Completable {
print("Do thingB Called\n")
return Completable.fromCallable {
print("calling stream B\n")
}
}
private fun doThingA(): Completable {
print("Do thingA Called\n")
return Completable.fromCallable {
print("calling stream A\n")
}
}
Observe that for the test below:
@Test
fun testCallAPlusB() {
doThingA().andThen(doThingB())
}
the output would be:
Do thingA Called
Do thingB Called
Quick note here: Observe that we are not subscribing to these Completables in this snippet.
For the test:
@Test
fun theTestSubscribe() {
doThingA().andThen(doThingB()).subscribe()
}
The output would be:
Do thingA Called
Do thingB Called
calling stream A
calling stream B
And lastly, in case first completable fails, the second completable would not be executed.
@Test
fun theTestFailThingA() {
doThingAFail().andThen(doThingB()).subscribe()
}
the output would be:
Do thingA Called
Do thingB Called
calling stream A
The key concept here is that the logic inside the method and inside the observable are executed not at the same time.
"Do thingA Called" and "Do thingB Called" lines will be printed once we call doThingA()
and doThingB()
methods. While the "calling stream A" and
"calling stream B" lines will only be called when someone subscribes to doThingA
and doThingB
methods.
The second concept here is how the andThen operator will handle errors. In the example above, in case doThingA()
completable ends up with an error, the stream will end and not print the "calling stream B" line.