Skip to content

Instantly share code, notes, and snippets.

@alexcohn
Last active February 9, 2021 21:01
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 alexcohn/ea582846901affa943102722f477a4a4 to your computer and use it in GitHub Desktop.
Save alexcohn/ea582846901affa943102722f477a4a4 to your computer and use it in GitHub Desktop.
Kotlin couroutines: SharedFlow emit from collect
import kotlinx.coroutines.*
import kotlinx.coroutines.flow.*
import java.util.concurrent.Executors
import kotlin.system.exitProcess
val dispatcher = Executors.newSingleThreadExecutor().asCoroutineDispatcher()
val scope = CoroutineScope(dispatcher)
fun main() {
val n = 1 // this will print 1 to 8, 42, and 9 and exit
val sharedFlow = MutableSharedFlow<Int>(n)
scope.launch {
for (i in 1..10) {
delay(30)
sharedFlow.emit(i)
}
}
scope.launch {
sharedFlow.collect {
println("collect: $it")
if (it == 8) {
sharedFlow.emit(42)
}
else if (it == 9) {
exitProcess(0)
}
}
}
}
@alexcohn
Copy link
Author

alexcohn commented Feb 9, 2021

if you set n=0, this hangs on 8.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment