Skip to content

Creating a state flow with state in

Devrath edited this page Jan 21, 2024 · 4 revisions

1682361921792

  • The shareIn is similar to stateIn but here the replay cache is set to 1
  • We can also check the existing value in the flow
  • We do not necessarily need to be collecting the flow to check the new value in the flow so we can check it directly also. code
private suspend fun generateDemoFlowTwo() = flow {
        repeat(1000){
            emit("Emitting value => $it")
            delay(2000)
        }
    }.stateIn(
        scope = viewModelScope
    )

    fun demoTwo() = viewModelScope.launch {
        
        println("Before second subscriber subscription -> ${generateDemoFlowTwo().value}")
        
        // Give a delay of 1 second before subscribing
        delay(1000)

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

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