Created
October 18, 2020 11:20
-
-
Save pencelab/f28b1a15e2e745f8fc84a254f947ba2b to your computer and use it in GitHub Desktop.
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.* | |
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