Wrap Callbacks as Coroutines (Kotlin/Android)

Swap callback hell for sexy suspend!

Charles Allen
1 min readSep 22, 2019

--

Available in: English, French, Thai

Kotlin coroutines provide a concise & elegant syntax for running concurrent & async tasks. Unlike callbacks, suspend funs can be wrapped & chained.

…but my legacy component only provides a callback interface

Android’s DatePicker & TimePicker dialogs are such a case! We just want a value from the user, but we cannot return that value directly, since the picker is launched asynchronously. So we’re stuck with ugly callbacks:

Traditional callback code (ugly)

Ewww.

Fortunately, Kotlin coroutines provide an extension precisely for this scenario: suspendCoroutine. This function suspends the current coroutine until the async task completes, resuming again once the result is ready:

Converted to coroutine code (sexy)

Of course, suspend funs can only be launched from a CoroutineScope. If you were looking closely you will see I swapped setOnClickListener for setOnClickCoroutine. Here it is; add it to your extension funs :)

Set suspendable click listeners (with this extension)

Dependencies

Further Reading & Resources

Refs & Credits

  1. Existing 3-function callback to Kotlin Coroutines (Roman Elizarov)
  2. Generic function to wrap callbacks with coroutines (rwhite226)
  3. Android Architecture Components + Coroutines (Android Developers)

More Voie Dev?

Follow on VoieDev.com, Medium, Dev.to, YouTube, Facebook, Twitter.
This article is available in
English, French, Thai.

--

--