Search code examples
kotlinrx-javarx-java2kotlin-flowrx-java3

RxJava BehaviorSubject#onError(Throwable) equivalent in Kotlin Flow


I'm converting some RxJava code to Kotlin Flow in a project.

I came across a piece of code where BehaviorSubject#onError(Throwable) was being called.

I didn't find any way to do it with a Flow object.

// RxJava
val behaviorSubject = BehaviorSubject.create<Int>()
behaviorSubject.onError(RuntimeException())

// Kotlin Flow
val mutableSharedFlow = MutableSharedFlow<Int>()
mutableSharedFlow.???

Is there any way to do it?


Solution

  • From the docs: "SharedFlow cannot be closed like BroadcastChannel and can never represent a failure. All errors and completion signals should be explicitly materialized if needed."

    So you'd probably have to create a data class with slots for values and the exception, then use takeWhile to stop it.

    (Sidenote: I happen to have a BehaviorSubject for kotlin flow that does offer an error channel.)