Skip to content

Convert ReceiveChannel<T> to Flow<T> without consuming #1490

@ZakTaccardi

Description

@ZakTaccardi

My ViewModel exposes a stream of events as a ReceiveChannel<T>

// in `ViewModel`
private val events = Channel(capacity = Channel.UNLIMITED) // these are "side effects"

fun events(): ReceiveChannel<T> = events

My activity/fragment observes this stream of events, without consuming on cancellation.

// in an Activity's onCreate

launch {
  for (event in viewModel.events()) {
    ui.handleEvent(event)
  }
}

By not consuming on cancellation (unsubscription), this allows my UI to re-use the same ReceiveChannel<T> instance across configuration changes.

// this exists already
fun <T> ReceiveChannel<T>.consumeAsFlow(): Flow<T>
// this does not
fun <T> ReceiveChannel<T>.asFlowWithoutConsuming: Flow<T>

I think the latter function would be useful. Can it be added?

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions