SharedFlow我认为收集数据是可以的onViewCreated。但是当我替换片段 n 次然后我触发一些事件时SharedFlow,它会向我发出 n 次事件而不是一个事件。
为了解决这个问题,我将代码放入onCreate片段中。我找不到任何相关文档。我是否遗漏了一些东西,或者我应该继续收集SharedFlow片段onCreate?
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
lifecycleScope.launchWhenResumed {
viewModel.uiEffect.collect {
when (it) {
is ViewEffectWrapper.PageEffect -> {
if (it.pageEvent is LoginViewEffect.OpenHomePage) {
startActivity(
Intent(
this@LoginFragment.context,
HomeActivity::class.java
)
)
}
}
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
这是我的SharedFlow定义ViewModel
private val _uiEffect = MutableSharedFlow<ViewEffectWrapper<LoginViewEffect>>(replay = 0)
val uiEffect: SharedFlow<ViewEffectWrapper<LoginViewEffect>> = _uiEffect
Run Code Online (Sandbox Code Playgroud) 我完全理解 suspendCoroutine 与 suspendCancellableCoroutine 在我的示例中是如何工作的。但我想知道为什么println("I finish") (第 13 行 - viewscope 块中的第二行)在我调用 viewScope.cancel() 之后执行。我可以在该行之前使用 isActive 标志修复它,但我不想检查每一行。我在那里缺少什么。我怎样才能取消范围?谢谢
import kotlinx.coroutines.*
import java.lang.Exception
import kotlin.coroutines.CoroutineContext
import kotlin.coroutines.resume
import kotlin.coroutines.suspendCoroutine
fun main() {
val parentJob = Job()
val viewScope = CoroutineScope(Dispatchers.IO + parentJob)
viewScope.launch {
println(tryMe())
println("I finished")
}
Thread.sleep(2000)
viewScope.cancel()
Thread.sleep(10000)
}
suspend fun tryMe() = suspendCoroutine<String> {
println("I started working")
Thread.sleep(6000)
println("Im still working :O")
it.resume("I returned object at the end :)")
}
suspend fun tryMe2() = suspendCancellableCoroutine<String> {
println("I …Run Code Online (Sandbox Code Playgroud)