Skip to content

Instantly share code, notes, and snippets.

@worker8
Last active July 4, 2022 14:10
Show Gist options
  • Save worker8/1d8368174cba2744a41eb0b7c35562b9 to your computer and use it in GitHub Desktop.
Save worker8/1d8368174cba2744a41eb0b7c35562b9 to your computer and use it in GitHub Desktop.
fun main() {
// coldFlow()
hotFlow()
}
fun coldFlow() {
val scope = CoroutineScope(Dispatchers.IO)
var count = 10
val coldFlow = flow {
while (count > 0) {
println("cold flow emitting...")
emit(count--)
delay(1000)
}
}
val favoriteAndWatchingChangedFlow: Flow<Int> =
coldFlow
.distinctUntilChanged()
scope.launch {
delay(5000)
favoriteAndWatchingChangedFlow.collect {
println("1st collector: $it")
}
}
scope.launch {
delay(5000)
favoriteAndWatchingChangedFlow.collect {
println("2nd collector: $it")
}
}
runBlocking {
delay(10_000)
}
}
fun hotFlow() {
val scope = CoroutineScope(Dispatchers.IO)
val _favoriteAndWatchingChangedFlow = MutableSharedFlow<String>()
var count = 10
val favoriteAndWatchingChangedFlow: Flow<String> =
_favoriteAndWatchingChangedFlow
.onEach { println("before shareIn") }
.distinctUntilChanged()
// .shareIn(scope, SharingStarted.Eagerly)
scope.launch {
while (count > 0) {
println("hot flow emitting...")
_favoriteAndWatchingChangedFlow.emit("hello world! $count")
delay(1000)
count--
}
}
scope.launch {
delay(5000)
favoriteAndWatchingChangedFlow.collect {
println("1st collector: $it")
}
}
scope.launch {
delay(5000)
favoriteAndWatchingChangedFlow.collect {
println("2nd collector: $it")
}
}
runBlocking {
delay(10_000)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment