简体   繁体   English

Flow块的collect会执行吗?

[英]Will the collect of the Flow block to execute?

I run the Code A and get the Result A. In my mind, it should be the Result B.我运行代码 A 并得到结果 A。在我看来,它应该是结果 B。

It seems that flow.collect { value -> println(value) } block to execute.似乎flow.collect { value -> println(value) }块要执行。

Will the collect of the Flow block to execute ? Flow块的collect会执行吗?

Code A代码 A

fun simple(): Flow<Int> = flow { 
    println("Flow started")
    for (i in 1..3) {
        delay(300)
        emit(i)
    }
}

fun main() = runBlocking<Unit> {
    println("Calling simple function...")
    val flow = simple()
    println("Calling collect...")
    flow.collect { value -> println(value) } //Block?
    println("Calling collect again...")   
}

Result A结果 A

Calling simple function...
Calling collect...
Flow started
1
2
3
Calling collect again...

Result B结果乙

Calling simple function...
Calling collect...
Flow started
Calling collect again...
1
2
3

BTW, I run Code 1 and get the result 1 as I expected.顺便说一句,我运行代码 1 并按预期获得结果 1。

Code 1代码 1

fun simple(): Flow<Int> = flow {
    for (i in 1..3) {
        delay(100) 
        emit(i) 
    }
}

fun main() = runBlocking<Unit> {  
    launch {
        for (k in 1..3) {
            println("I'm not blocked $k")
            delay(100)
        }
    }  
    simple().collect { value -> println(value) } 
}

Result 1结果 1

I'm not blocked 1
1
I'm not blocked 2
2
I'm not blocked 3
3

Suspend functions do not block, but they are synchronous, meaning the execution of the code in the coroutine waits for the suspend function to return before continuing.挂起函数不会阻塞,但它们同步的,这意味着协程中代码的执行会等待挂起函数返回,然后才能继续。 The difference between suspend function calls and blocking function calls is that the thread is released to be used for other tasks while the coroutine is waiting for the suspend function to return.挂起函数调用和阻塞函数调用的区别在于,在协程等待挂起函数返回的同时,线程被释放以用于其他任务。

collect is a suspend function that internally calls its lambda repeatedly and synchronously (suspending, not blocking) and doesn't return until the Flow is completed. collect是一个挂起函数,它在内部重复且同步地(挂起,不阻塞)调用其 lambda,并且在 Flow 完成之前不会返回。

launch is an asynchronous function that starts a coroutine. launch是一个启动协程的异步函数。 It returns immediately without waiting for its coroutine to complete, which is why Code 1 behaved as you expected.它立即返回而无需等待其协程完成,这就是代码 1 表现如您所愿的原因。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM