Skip to content

Creating a Shared Flow with Shared‐In

Devrath edited this page Jan 21, 2024 · 4 revisions

How the SharedIn operator is useful

Using the SharedIn operator, We can convert the cold flow into a hot flow!

3 ways of converting to hot flow using shared-in

  • Eagerly -> Emission will start even if no subscribers are there
  • Lazily --> Emission will start on for first subscribers
  • WhileSubscribed -> Emission will start when there are subscribers and end when there are no subscribers

output

Collected value (A) => Emitting value => 0
Collected value (A) => Emitting value => 1
Collected value (A) => Emitting value => 2
Collected value (A) => Emitting value => 3
Collected value (A) => Emitting value => 4
Collected value (A) => Emitting value => 5
Collected value (A) => Emitting value => 6
Collected value (A) => Emitting value => 7
Collected value (A) => Emitting value => 8
app_time_stats: avg=347.29ms min=3.81ms max=16603.19ms count=50 //Here second subscriber joins
Collected value (B) => Emitting value => 0
Collected value (A) => Emitting value => 9
Collected value (B) => Emitting value => 1
Collected value (A) => Emitting value => 10
Collected value (B) => Emitting value => 2
Collected value (A) => Emitting value => 11
Collected value (B) => Emitting value => 3

code

class StateAndSharedFlowsDemoVm @Inject constructor(
    @ApplicationContext private val context: Context,
) : ViewModel() {

    // Cold Flow
    private fun generateDemoFlow() = flow {
        repeat(1000){
            emit("Emitting value => $it")
            delay(2000)
        }
    }.shareIn(
        scope = viewModelScope,
        started = SharingStarted.WhileSubscribed(),
        replay = 5
    )

    fun demo()  = viewModelScope.launch{
        // Give a delay of 1 second before subscribing
        delay(1000)

        generateDemoFlow().collect{
            println("Collected value (A) => $it")
        }
    }

    fun addNewSubscriber() = viewModelScope.launch{
        generateDemoFlow().collect{
            println("Collected value (B) => $it")
        }
    }
}
Clone this wiki locally