Skip to content

Instantly share code, notes, and snippets.

@realdadfish
Created February 7, 2023 11:53
Show Gist options
  • Save realdadfish/63773e600d0bebb36ce3d078978c02b4 to your computer and use it in GitHub Desktop.
Save realdadfish/63773e600d0bebb36ce3d078978c02b4 to your computer and use it in GitHub Desktop.
Why does my shared flow subscription not complete after the scope it's shared in is canceled?
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.cancel
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.flow.onCompletion
import kotlinx.coroutines.flow.shareIn
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
val scope = CoroutineScope(Job() + Dispatchers.Default)
val flow: Flow<Int> = flow {
var count = 0
while (true) {
emit(count++)
delay(1000)
}
}
val shared = flow.shareIn(scope, SharingStarted.WhileSubscribed())
fun main() {
runBlocking {
val job = launch {
shared.onCompletion { println("complete") }.collect { println(it) }
}
delay(5000)
scope.cancel()
println("isActive: " + job.isActive)
println("isCancelled: " + job.isCancelled)
job.join()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment