Android Coroutine function callback

Viewed 1692

Here is my fun in the Repository that returns me the String Id from the Group name

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

And this is the function on the ViewModel

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

Now I want this group Id on the Activity side what I need to do?

3 Answers

You can use callback by using Higher order function as callback parameter to provide data back to calling method like below :

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

This method would be used like below in your Activity:

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

You can use an interface something like :-

interface GroupIdViewContract{ fun returnId(groupId : String) }

in ViewModel

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

then you can implement this interface in your activity and you can easily get this group id in your activity

That's what you need Callbacks and Kotlin Flows. For example Single-shot callback:

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)
        }
    }
}
Related