https://kotlinlang.org logo
Title
c

Cấn Văn Nghị

05/21/2023, 11:03 AM
Hi I have a question about cancelling a flow, could you please help?
runBlocking {
            val job = launch {
                channelFlow {
                    callbackFlow {// How can I cancel this flow when call job.cancel
                        var count = 0
                        while (isActive) {
                            trySend(count)
                            count++
                            Log.d("TAG", count.toString())
                        }
                        awaitClose()
                    }
                        .flowOn(<http://Dispatchers.IO|Dispatchers.IO>)
                        .collectLatest {
                            trySend("callbackFlow value - $it")
                            Log.d("TAG", "callbackFlow value - $it")
                        }
                }
                    .collect()
            }

            delay(1000L)
            Log.d("TAG", "cancel is called")
            job.cancel()
        }
While loop still runs and logs some values after called
job.cancel()
How can I cancel while loop immediately call
job.cancel()
?