Corounies Launch and Async

Within Coroutines, we aren’t limited to only creating async tasks and having background tasks like this:

We can use launch(UI), or async(UI). The difference is, async(UI) can actually return a value. The launch(UI) returns Unit so it can’t. Since async(UI) has this ability to return a value this would be perfect to place into a function! Having the ability to place this async(UI) inside a function, we can actually hide some of our code within other classes and not take up so much space. Dedicating one function for each task such as this:

This Deferred<String> means this function returns a value that isn’t a value yet. It needs to be called with getNetworkResultAndUpdateUI().await() in order to be used. With the .await() the value turns into a String instead of the Deferred<String>.

But since this is a Deferred value, it can’t be used on the main thread! It needs to be used within a launch(UI) or an async(UI). We’re going to be using the launch(UI) because we don’t need a return value.

Leave a Reply

Your email address will not be published. Required fields are marked *