niq*_*eco 5 android kotlin-coroutines dagger-hilt
如果我的应用程序中有一个带有注释的类,@ActivityRetained
那么能够访问将被适当取消的协程作用域是有意义的。它类似于viewModelScope
a 中的ViewModel
。
这是可以做的事情还是仍然需要实施的事情?
小智 0
我一直在努力解决同样的问题,但最后我在这里找到了解决方案
您可以创建自己的CoroutineScope
生命周期:
class RetainedLifecycleCoroutineScope(
val lifecycle: RetainedLifecycle,
) : CoroutineScope, RetainedLifecycle.OnClearedListener {
override val coroutineContext: CoroutineContext = SupervisorJob() + Dispatchers.Main.immediate
init {
lifecycle.addOnClearedListener(this)
}
override fun onCleared() {
coroutineContext.cancel()
}
}
Run Code Online (Sandbox Code Playgroud)
并像这样使用它:
@ActivityRetainedScoped
class UseCase @Inject constructor(
activityRetainedLifecycle: ActivityRetainedLifecycle,
) {
private val coroutineScope = RetainedLifecycleCoroutineScope(activityRetainedLifecycle)
}
Run Code Online (Sandbox Code Playgroud)