Search code examples
androidkotlinkotlinx.coroutines

Android Coroutine function callback


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?


Solution

  • 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
    }