1

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?

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.