Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 359
Jaydip Umaretiya Avatar asked Aug 28 '26 00:08

Jaydip Umaretiya


1 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
}
like image 184
Jeel Vankhede Avatar answered Aug 29 '26 16:08

Jeel Vankhede