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()
Currently,
kotlinx.coroutinesprovides:and
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:This would provide a clean, zero-overhead way to expose hot flows as a plain
Flowinterface.Use cases
APIdesign where implementation details (SharedFlow/StateFlow) should not leak.replayCache,subscriptionCount, orvalue.Flowimplementations.