Skip to content

Add asFlow() extension for SharedFlow #4530

@g000sha256

Description

@g000sha256

Currently, kotlinx.coroutines provides:

fun <T> MutableSharedFlow<T>.asSharedFlow(): SharedFlow<T>

and

fun <T> MutableStateFlow<T>.asStateFlow(): StateFlow<T>

to hide mutability.

However, there's no convenient way to hide the "hot flow" nature and return a simple Flow<T> that cannot be cast back to the original type. I suggest to add:

fun <T> SharedFlow<T>.asFlow(): Flow<T>

This would provide a clean, zero-overhead way to expose hot flows as a plain Flow interface.

Use cases

  • API design where implementation details (SharedFlow/StateFlow) should not leak.
  • Preventing clients from accessing replayCache, subscriptionCount, or value.
  • Consistent return types in interfaces that may use different Flow implementations.
private val _mutableSharedFlow = MutableSharedFlow<Value>()
override val values: Flow<Value> = _mutableSharedFlow.asFlow()

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions