Home > Back-end >  Assign a variable to the result of a call inside a coroutine
Assign a variable to the result of a call inside a coroutine

Time:09-19

Is there a one-liner for this?

...
var x = ""
coroutine.launch {
    x = StoreHelper.getProductPrice(mdProducts[0].id)
}
return x

CodePudding user response:

You shouldn't rely that variable x will have a different value apart from "" in that case. Coroutines run asynchronously, so the x can be returned with value "" before the code StoreHelper.getProductPrice() runs.

You can rewrite the code to something like the following:

coroutine.launch {
    val x = StoreHelper.getProductPrice(mdProducts[0].id)
    // do smth with x
}

but you can't return x from the function in this case.

And as per my knowledge there is no one-liner for that.

CodePudding user response:

You might want to use async instead, which returns a Deferred

return coroutine.async { StoreHelper.getProductPrice(mdProducts[0].id) }

and later you can await the result in a coroutine - or if you want to use the experimental getCompleted function and hope it's completed, you can do that. Not the best idea for handling an asynchronous result though, await is what you should really be using.

Bear in mind that this is the whole issue with async code - stuff happens simultaneously, some things take longer than others, so you need a way to handle the results when they're ready. You can't return x until you have it, so you either need to block until the coroutine finishes, or return something like the Deferred (which is like a Java Future) so you have a reference to the running job you can check later. Or don't return a result at all, and just have that job do something when it's finished, like calling a function.

This section on async functions might be helpful to look through, to give you some ideas about what you need and what you can do.

  • Related