2

Newbie question with coroutines :-)

With coroutines that doesn't return a value, is there a way to execute some code upon the completion of that coroutine ?

In this example, funcA() performs some async call and upon completion funcB, funcC needs to complete, the rest of the code can continue to execute independent of funcA() completion

... other code executing
... other code executing

launch {
  funcA()
}
funcB()
funcC()

... other code executing
... other code executing

One approach would be to enclose funcB, funcC within a method and we can use async with await ... but why return a value just for that.

i.e.

executeFunBC()
{
  funcB()
  funcC()
}


launch {
 val result = funcA()
}
 executeFunBC(result).await()

Basically, in some languages you can use 'blocks' or closures and execute some code upon completion of that block in the same method. (similar to callbacks)

Back to my question:

Is there a way to define the execution of funcB, funcC upon the completion of funcA() in the same function ?

1 Answer 1

2

It's very simple, just do this:

launch {
  funcA()

  // Will not execute until funcA() returns
  funcB() 
  funcC()
}

but make sure you use a dispatcher that works for funcB() and funcC(), e.g. like this launch(Dispatchers.Main) {.

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.