https://kotlinlang.org logo
#coroutines
Title
# coroutines
n

Natsuki(开元米粉实力代购)

03/22/2021, 7:56 AM
in my understanding, the first code fragment should behavior the same as the latter one, coz launch w/o explicit receiver adds the new created coroutine as a child of current coroutine, so cancel the collectLatest block will cause the child coroutine to cancel, which should leads to the same result as the latter code fragment
🧵 3
k

knthmn

03/22/2021, 8:31 AM
I assume in both examples, you are wrapping the call in something that provides a
CoroutineScope
as a receiver (e.g.
runBlockng()
). In the first example, the
launch
is from the
CoroutineScope
receiver, i.e. it is equivalent to
Copy code
fun main() = runBlocking { // this: CoroutineScope
    flow {
       // ...
    }.collectLatest { value ->
        this@runBlocking.launch { // (coroutineScope from runBlocking).launch()
            println("start: $value")
            while(true) {
                delay(200L)
                println("loop: $value")
            }
        }
    }
}
which it just launches the
Job
and returns in
collectLatest()
instantly and never canceled by
collectLatest()
. However, in the second case,
coroutineScope()
provides the
CoroutineScope
of the current coroutine, which is the one provided by
collectLatest()
and can be cancelled by it.
💯 1
n

Natsuki(开元米粉实力代购)

03/22/2021, 2:04 PM
thats exactly the case, thank you
2 Views