Kotlin中SharedFlow的emit与tryEmit有什么差别

如果当你在ViewModel中宣告一个SharedFlow

https://kotlinlang.org/api/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.flow/-shared-flow/

val shareFlow = MutableShareFlow<Int>()

在使用时候你会发现emit是一个suspend function ,所以都必须透过coroutineScope来呼叫

class MyViewModel: ViewModel{    val shareFlow = MutableShareFlow<Int>()    fun test() {        viewModelScope.launch {            shareFlow.emit(3)        }    }}

然后你会发现,他其实有一个tryEmit,而且还不需要透过coroutineScope来执行,这样不是超级方便的吗,少写很多行

结果你发现你改写这样后

class MyViewModel: ViewModel{    val shareFlow = MutableShareFlow<Int>()    fun test() {                shareFlow.tryEmit(3)            }}

居然就没反应了,先说结果,其实你误用tryEmit这个funciton了

根据说明

https://kotlinlang.org/api/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.flow/-mutable-shared-flow/try-emit.html

tryEmit 其实他是当下让你用来测试当下是否能够进行emit,如果buffer已经满了,他回透过回传boolean来告诉你,你可以藉着进行一些处理

因此不要会误以为tryEmit就是一个不需要加上coroutineScope的方法。


关于作者: 网站小编

码农网专注IT技术教程资源分享平台,学习资源下载网站,58码农网包含计算机技术、网站程序源码下载、编程技术论坛、互联网资源下载等产品服务,提供原创、优质、完整内容的专业码农交流分享平台。

热门文章