AbhinavChoudhury
AbhinavChoudhury

Reputation: 1187

Android Kotlin async/coroutines usage

I have a function that runs on the Android main thread (UI thread):

fun someFunc() {

  ...
  doSomething1()
  doSomething2()
  doSomething3()
  ...
}

I want to run doSomething2() asynchronously in a background thread and make sure that someFunc() is suspended (not blocked) until this execution completes. Once done, someFunc() should resume in the main thread (from doSomething3()). During this background thread execution, I want to make sure that main thread is free and not blocked.

I know this can be done using Futures, but I'm wondering how to do this using coroutines/async?

Upvotes: 1

Views: 452

Answers (1)

Sergio
Sergio

Reputation: 30595

You can call those functions in a coroutine, launched using viewModelScope in a ViewModel class or lifecycleScope in Activity/Fragment:

fun someFunc() = viewModelScope.launch {

  doSomething1()
  doSomething2()
  doSomething3()

}

suspend fun doSomething2() = withContext(Dispatchers.IO) {
    ...
}

To run doSomething2() in a background thread we need to switch context of the coroutine to Dispatchers.IO using withContext() function.

Upvotes: 1

Related Questions