Created
October 18, 2020 11:21
-
-
Save pencelab/4c289ed253583cc1350ed5255662b34c 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 job1 = launch(Dispatchers.Default) { | |
myComponent.myRandomFlow | |
.collect { | |
log("Job #1 - Collected: $it") | |
} | |
} | |
val job2 = launch(Dispatchers.Default) { | |
delay(2500) | |
myComponent.myRandomFlow | |
.collect { | |
log("Job #2 - Collected: $it") | |
} | |
} | |
launch { | |
repeat(5) { | |
myComponent.updateRandom() | |
delay(1000) | |
} | |
job1.cancel() | |
job2.cancel() | |
} | |
} | |
log("End") | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment