Android协程函数回调

标签 android kotlin kotlinx.coroutines

这是我在 Repository 中的乐趣,它从组名中返回字符串 ID

@Suppress(“RedundantSuspendModifier”)
@WorkerThread
suspend fun fetchGroupId(groupName: String): String {
      return groupDao.fetchGroupId(groupName)
}

这是 ViewModel

上的函数
fun getGroupId(groupName: String) = scope.launch(Dispatchers.IO) {
      groupId = repository.fetchGroupId(groupName)
}

现在我想在 Activity 端使用这个组 ID 我需要做什么?

最佳答案

您可以通过使用高阶函数作为回调参数来使用回调来将数据提供回调用方法,如下所示:

fun getGroupId(groupName: String, callback: (Int?) -> Unit) = scope.launch(Dispatchers.IO) {
    callback(repository.fetchGroupId(groupName))
}

此方法将在您的 Activity 中使用,如下所示:

mViewModel.getGroupId("your group name here") { id ->
    // Here will be callback as group id
}

关于Android协程函数回调,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54108446/

相关文章:

jvm - Kotlin 中的 COROUTINE_SUSPENDED 和 suspendCoroutineOrReturn

kotlin - 使用 NotBlank 注释在 Kotlin 代码中不起作用

kotlin - 如何异步映射序列

android - Android声音重叠命令行ffmpeg不起作用

android - 使用 Intent 时 Activity 意外停止

Android:AsyncTask 中的进度对话框未显示

gradle - SonarQube detekt gradle插件中是否有gradle设置以在远程主机上而不是在文件中生成报告

android - Kotlin 协程 : RxJava-like subscribe to running job/Check if coroutine is running

kotlin - 为什么 CoroutineExceptionHandler 没有捕获/处理我的异常?

android - SQLite 查询仅针对特定列崩溃 - 无法读取第 0 行,第 -1 列