Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pencelab/f28b1a15e2e745f8fc84a254f947ba2b to your computer and use it in GitHub Desktop.
Save pencelab/f28b1a15e2e745f8fc84a254f947ba2b to your computer and use it in GitHub Desktop.
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