Is it possible to cancel a sharedIn cold flow?
# coroutines
h
Is it possible to cancel a sharedIn cold flow?
Copy code
@Test
    fun a() = runTest(dispatchTimeoutMs = 1.seconds.inWholeMilliseconds) {
        val listener = flow {
            var i = 0
            while (currentCoroutineContext().isActive) {
                emit(i)
                i++
                yield()
                println("FLOW $i")
            }
        }.shareIn(this, SharingStarted.WhileSubscribed(replayExpiration = ZERO))

        launch {
            listener.collect {
                if (it == 1) {
                    println("COLLECT $it")
                    cancel()
                }
            }
        }
    }
I would expect
listener
will be canceled because I use
WhileSubscribed
and the only subscriber is canceled
z
That expectation makes sense to me - what are you observing?
h
The famous error message:
kotlinx.coroutines.test.UncompletedCoroutinesError: After waiting for 1000 ms, the test coroutine is not completing, there were active child jobs: ["coroutine#2":StandaloneCoroutine{Active}@34f6515b]
. And I don't know, which is the active child job.