Android Coroutine函数回调

时间:2019-01-09 10:51:30

标签: android kotlin kotlinx.coroutines

这是我在存储库中的乐趣,该信息从组名中返回字符串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)
}

现在我要在“活动”端将此组ID做什么?

3 个答案:

答案 0 :(得分:1)

您可以使用类似:-

的界面
interface GroupIdViewContract{ fun returnId(groupId : String) }

在ViewModel中

fun getGroupId(groupName: String) = scope.launch(Dispatchers.IO) {
groupId = repository.fetchGroupId(groupName)
viewContract?.returnId(groupId)
}

然后您可以在活动中实现此接口,并且可以在活动中轻松获取此组ID

答案 1 :(得分:1)

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

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
}

答案 2 :(得分:0)

这就是您需要的Callbacks and Kotlin Flows。 例如单次回调:

interface Operation<T> {
    fun performAsync(callback: (T?, Throwable?) -> Unit)
}


suspend fun <T> Operation<T>.perform(): T =
suspendCoroutine { continuation ->
    performAsync { value, exception ->
        when {
            exception != null -> // operation had failed
                continuation.resumeWithException(exception)
            else -> // succeeded, there is a value
                continuation.resume(value as T)
        }
    }
}