Consider the following code:
fun CoroutineScope.createExposedSharedFlow(): SharedFlow<Int> {
return flow<Int> { }.shareIn(this, started = SharingStarted.Lazily)
}
fun CoroutineScope.createEncapsulatedSharedFlow(): Flow<Int> {
return flow<Int> { }.shareIn(this, started = SharingStarted.Lazily)
}
fun CoroutineScope.createEncapsulatedSharedFlow(onSubscription: suspend FlowCollector<Int>.() -> Unit): Flow<Int> {
return flow<Int> { }.shareIn(this, started = SharingStarted.Lazily).onSubscription(onSubscription)
}
suspend fun useFlows() = coroutineScope {
createExposedSharedFlow().onSubscription {
// do something
}
createEncapsulatedSharedFlow().onSubscription {
// does not compile
}
createEncapsulatedSharedFlow {
// do something
}
}
What is the best way to work with SharedFlow?
- Exposing
SharedFlowcompletely, thereby exposing an implementation detail of the function. - Not exposing
SharedFlow, thereby losing access toonSubscribeand otherSharedFlowspecific functionality outside the function. - Not exposing
SharedFlow, but exposingonSubscribeas a parameter to the function.