这是我在 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/