0

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?

akarnokd
  • 69,132
  • 14
  • 157
  • 192
Augusto Carmo
  • 4,386
  • 2
  • 28
  • 61
  • 1
    From the [docs](https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.flow/-shared-flow/): "SharedFlow cannot be closed like BroadcastChannel and can never represent a failure. All errors and completion signals should be explicitly materialized if needed." – akarnokd Jun 03 '21 at 07:21
  • @akarnokd thank you very much for the reply. I became aware of that yesterday after some more research. The thing is that I wanted to use a different structure, which I shouldn't. Do you mind posting what you've just written so I can mark it as the correct answer? Thanks again ^^ – Augusto Carmo Jun 03 '21 at 12:42

1 Answers1

1

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.)

akarnokd
  • 69,132
  • 14
  • 157
  • 192