Image for post
Image for post
Illustration by Virginia Poltrack

Coroutines On Android (part III): Real work

Sean McQuillan
May 21, 2019 · 12 min read

Solving real-world problems with coroutines

One shot requests

A one shot request is performed each time it’s called. It stops executing as soon as a result is ready.

Problem: Displaying a sorted list

As a general pattern, start coroutines in the ViewModel.

A repository should prefer to expose regular suspend functions that are main-safe.

Suspend functions in Room are main-safe and run on a custom dispatcher.

The one shot request pattern

Our first bug report!

When starting a new coroutine in response to a UI event, consider what happens if the user starts another before this one completes.

The best solution: Disable the button

Disabling the buttons while a sort runs using _sortButtonsEnabled in sortPricesBy.

Concurrency patterns

Using cancelPreviousThenRun to ensure that only one sort runs at a time.

Consider building abstractions to avoid mixing ad-hoc concurrency patterns with application code.

A Mutex lets you ensure only one coroutine runs at a time — and they will finish in the order they started.

Join previous work is a great solution to avoiding repeated network requests.

What’s next?

Android Developers

The official Android Developers publication on Medium

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch

Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore

Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store