Kotlin Flow - is it possible to add new values on demand

Viewed 645

Is it possible to add values to the flow after it was created?

So far I have seen flow builder examples where the builder defines which values will be emitted and when. However, what if I need to create a flow and subscribe to it on UI layer before any value is produced. Then I need to add values to it in a different layer (e.g. domain). So I thought I would create an empty flow builder and then add values, but it does not work. This model works with Channels, but I do not want to use deprecated API, see below. I would like a mechanism which would connect domain and UI layers and would be observable. Another problem with Channels is that I cannot clear data inside of it, the last value always seems to stay there.

private val channel = ConflatedBroadcastChannel<Data>()

override val flow: Flow<Data> = flow {
    channel.consumeEach { data ->
        this.emit(data)
    }
}
override suspend fun setGraph(domainData: Data) {
    channel.send(domainData)
}
1 Answers

You were on the right track with the idea of using Channel and exposing it as Flow, the only missing part is the Channel.asFlow() extension function, see docs.

However, I think your question is duplicate of this question, which has been already answered. (I would post this as a comment, but I don't have enough reputation.)

Related