3

I tried using Kotlin Flow to be some kind of message container which should pass this message to all observers (collectors). I do not want to use LiveData on purpose because it need to be aware of lifecycle.

Unfortunately I have noticed that if one collector collects message from flow no one else can receive it.

What could I use to achieve "one input - many output".

Dominik
  • 1,233
  • 2
  • 14
  • 29

2 Answers2

5

You can use StateFlow or SharedFlow, they are Flow APIs that enable flows to optimally emit state updates and emit values to multiple consumers.

From the documentation, available here:

StateFlow: is a state-holder observable flow that emits the current and new state updates to its collectors. The current state value can also be read through its value property.

SharedFlow: a hot flow that emits values to all consumers that collect from it. A SharedFlow is a highly-configurable generalization of StateFlow.

A simple example using state flow with view model:

class myViewModel() : ViewModel() {

  val messageStateFlow = MutableStateFlow("My inicial awesome message")

}

You can emit a new value using some scope:

yourScope.launch {
    messageStateFlow.emit("My new awesome message")
}

You can collect a value using some scope:

yourScope.launch {
    messageStateFlow.collect {
        // do something with your message
    }
}

Attention: Never collect a flow from the UI directly from launch or the launchIn extension function to update UI. These functions process events even when the view is not visible. You can use repeatOnLifecycle as the documentation sugests.

-1

You can try BehaviorSubject from rxJava. Is more comfortable to use than poor kotlin.flow. Seems like this link is for you: BehaviorSubject vs PublishSubject

val behaviorSubject = BehaviorSubject.create<MyObject> {
    // for example you can emit new item with it.onNext(), 
    // finish with error like it.onError() or just finish with it.onComplete()
    somethingToEmit()
}

behaviorSubject.subscribe {
    somethingToHandle()
}
Link182
  • 733
  • 6
  • 15