Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
import kotlinx.coroutines.*
import kotlinx.coroutines.flow.*
fun log(message: String) {
println("[${Thread.currentThread().name}] : $message")
}
class MyComponent {
private val _myRandomFlow = MutableStateFlow("Initial Value -> ${getRandom()}")
val myRandomFlow: StateFlow<String>
get() = _myRandomFlow
fun updateRandom() {
val update = "Random -> ${(1..100).random()}"
log("Updating: $update")
_myRandomFlow.value = update
}
private fun getRandom() = (1..100).random()
}
fun main() {
log("Start")
val myComponent = MyComponent()
runBlocking {
val job = launch(Dispatchers.Default) {
myComponent.myRandomFlow
.collect {
log("Collected: $it")
}
}
launch {
repeat(5) {
myComponent.updateRandom()
delay(1000)
}
job.cancel()
}
}
log("End")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.