Kotlin Flow Replay Functionality

Viewed 1866

Is there a planned or existing way to replicate RX's replay/refcount functionality in Kotlin Flow?

I need something between a broadcast channel's multicast facility (so consumers don't fight over events), and a regular channel's caching/suspension functionality (so consumers receive some backlog of events).

2 Answers

Maybe a bit late, but still might be useful. There's an open issue to implement this behavior, so sooner or later we'll have it. Also, there's a discussion about connectable flow, but I can't see decision of they implementing it or not.

UPD: Looks like KEEP-1261 is outdated and 1716 is more relevant now.

Kotlin Flow current support shareIn function to replays the last emitted item to a new collector. Snippet code from StateFlow and SharedFlow:

val latestNews : Flow<List<ArticleHeadline>> = flow {
    ...
}.shareIn(
    externalScope,
    replay = 1,
    started = SharingStarted.WhileSubscribed()
)
Related