Created
May 29, 2022 08:03
-
-
Save sasssass/0a80a9c1827915c4678b5c0fc2dec19a to your computer and use it in GitHub Desktop.
stateFlow.kt
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import kotlinx.coroutines.* | |
import kotlinx.coroutines.flow.* | |
lateinit var collectingStateFlowJob : Job | |
fun main() = runBlocking{ | |
val stateFlowHelper = StateFlowHelper() | |
launch { | |
stateFlowHelper.emit() | |
} | |
var collectingCounter = 0 | |
collectingStateFlowJob = launch { | |
stateFlowHelper.stateFlowData.collect{ collected -> | |
collected?.let { | |
println(it) | |
if(++collectingCounter == 2) | |
collectingStateFlowJob.cancel() // if we won't cancel this job the program won't stop | |
// because of collecting | |
} | |
} | |
} | |
launch { | |
stateFlowHelper.emit() | |
} | |
print("") | |
} | |
class StateFlowHelper{ | |
private val _stateFlowData : MutableStateFlow<String?> = MutableStateFlow(null) | |
val stateFlowData = _stateFlowData.asStateFlow() | |
var counter = 0 | |
suspend fun emit(){ | |
println("Start to emit") | |
_stateFlowData.emit("Hi I'm State Flow number ${++counter}") | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment