Android kotlin set SharingStarted property of MutableSharedFlow without "shareIn" operator

Viewed 175

My particular implementation concerns the use of kotlin flows in Android, but I guess this is applicable to kotlin in general.

What I would like to do is to set my SharedFlow to be started according to the SharingStarted.WhileSubscribed() started policy, so that the flow materializes only when the number of subscribers is greater than zero.

The recommended way to setup such a flow from the android official guide is to use the shareIn operator:

val latestNews: Flow<List<ArticleHeadline>> = flow {
        ...
        // emit() here
}.shareIn(
    externalScope,
    replay = 1,
    started = SharingStarted.WhileSubscribed()
)

In my case, I want to emit only under specific conditions that are independent from the flow itself, so it is unpractical to emit inside the flow{ ... } body. As a consequence, I created a MutableSharedFlow and use tryEmit to emit whenever I need to, for example upon a method call:

// Backing property to avoid flow emissions from other classes
private val _tickFlow = MutableSharedFlow<Int>(replay = 1, onBufferOverflow = BufferOverflow.DROP_OLDEST)
val tickFlow: SharedFlow<Int> = _tickFlow

// called after domain logic deciding which number to emit
fun timeToEmit(num:Int){
   _tickerFlow.tryEmit(num) 
}

What is the SharingStarted policy (if any) of a flow created through the MutableSharedFlow<>() constructor?
How can I set this flow SharingStarted property to be started (materialized) only when the number of subscribers is greater than 0?

0 Answers
Related