Should a function creating a SharedFlow expose or not expose SharedFlow or SharedFlow specific features?

33 views Asked by At

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?

  1. Exposing SharedFlow completely, thereby exposing an implementation detail of the function.
  2. Not exposing SharedFlow, thereby losing access to onSubscribe and other SharedFlow specific functionality outside the function.
  3. Not exposing SharedFlow, but exposing onSubscribe as a parameter to the function.
0

There are 0 answers