Reputation: 11
I'm using Kotlin + Reactor (Mono and Flux) and I wanna know the difference between using await...()
(from kotlin-coroutines-reactive) function and subscribe()
(from Reactor). I brought two examples to show what I'm trying to do.
Example 1 (with await function):
@Test
internal fun test() = runBlockingTest {
Mono.error<String>(IllegalStateException("exception"))
.doOnError {
print("error")
}.awaitFirst().let {
print("success")
}
}
Output: "error" with the IllegalStateException stack trace.
Example 2 (with subscribe function):
@Test
internal fun test() = runBlockingTest {
Mono.error<String>(IllegalStateException("exception"))
.doOnError {
print("error")
}.subscribe {
print("success")
}
}
Output: Just "error".
Why example 1 shows the stack trace and example 2 doesn't show?
Thanks.
Upvotes: 1
Views: 1909
Reputation: 9947
When you call subscribe
on a reactive chain you decouple it from the main flow, it becomes independent and potentially asynchronous. Error is travelling on the reactive stream as a signal rather than as a traditionally thrown exception. In this case error handling is the responsibility of the reactive chain using operators like doOnError
, onErrorMap
, onErrorReturn
, etc.
On the other hand Kotlin's await
breaks this independence and attaches the reactive stream back to the main flow and lets you write reactive/asynchronous code as it would be imperative (e.g.: try-catch blocks, unwrapped function return types, etc.).
Upvotes: 1