MutableStateFlow value 和 emit 之间的区别

MutableStateFlow difference between value and emit

在 MutableStateFlow 上使用 value end emit fun 有什么区别?

fun main() = runBlocking {

    val mutable = MutableStateFlow(0)

    launch {
        mutable.collect {
            println(it)
        }
    }

    mutable.value = 1
    mutable.emit(2)
}

emit() 是一个挂起函数,它包装了一个设置值的调用:

override suspend fun emit(value: T) {
    this.value = value
}

所以不同之处在于 value 即使不在协程中也允许您设置值。 emit() 存在,因此 MutableStateFlow 可以继承自 MutableSharedFlow。

Source code here.