Android协程函数回调

Android Coroutine function callback

这是我在 存储库 中的乐趣,returns 我从组名

中获取字符串 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我需要做什么?

您可以使用类似这样的界面:-

interface GroupIdViewContract{ fun returnId(groupId : String) }

在 ViewModel 中

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

然后你可以在你的activity中实现这个接口,你可以很容易地在你的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
}

这就是您所需要的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)
        }
    }
}