如何在MainActivity中管理协同程序,并等待完成? [英] How to manage coroutines in MainActivity with waiting until done?

查看:118
本文介绍了如何在MainActivity中管理协同程序,并等待完成?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在MainActivity中使用GlobalScoperunBlocking,但我没有使用那里的流只是暂停函数。我想将GlobalScope从协程更改为其他作用域。

使用案例

class UpdateNotificationListItemUseCase @Inject constructor(private val notificationDao: NotificationDao): BaseUpdateBooleanUseCase<Int, Boolean, Boolean, Boolean, Unit>() {
    override suspend fun create(itemId: Int, isRead: Boolean, isArchived: Boolean, isAccepted: Boolean){
        notificationDao.updateBooleans(itemId, isRead, isArchived, isAccepted)
    }
}

维护活动

val job = GlobalScope.launch { vm.getIdWithUpdate() }
runBlocking {
    job.join()
}

MainViewModel

suspend fun getIdWithUpdate() {
     var id = ""
     id = notificationAppSessionStorage.getString(
            notificationAppSessionStorage.getIncomingKeyValueStorage(),
            ""
        )
        if (id != "") {
           
            updateNotificationListItemUseCase.build(id.toInt(), true, false, false)
        }
    }
}

我的建议:

我已阅读文档https://developer.android.com/kotlin/coroutines/coroutines-best-practices

val IODispatcher: CoroutineDispatcher = Dispatchers.IO
val externalScope: CoroutineScope = CoroutineScope(IODispatcher)
      suspend {
         externalScope.launch(IODispatcher) {
              vm.getIdWithUpdate()
         }.join()
      }

第二个选项,但在这里我不会等到作业完成

suspend {
     withContext(Dispatchers.IO) {
          vm.getIdWithUpdate()
     }
}

你觉得这件事怎么样? 它不是提供给ANR的吗,我也阻止线程。

推荐答案

您可以使用MainActivity中的lifecycleScope,而不是GlobalScope来启动协程:

lifecycleScope.launch { 
    vm.getIdWithUpdate() // calling suspend function
    // here suspend function `vm.getIdWithUpdate()` finished execution
    // ... do something after suspend function is done
}

要使用lifecycleScope添加依赖项:

implementation 'androidx.lifecycle:lifecycle-runtime-ktx:$2.4.0'
        

GlobalScope非常不鼓励使用。而且不需要调用job.join(),可以在调用vm.getIdWithUpdate()后在协程构建器块中做一些事情,例如更新UI。此协程正在使用Dispatchers.Main上下文运行。

这篇关于如何在MainActivity中管理协同程序,并等待完成?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆