如果当你在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
的方法。