Wrap Callbacks as Coroutines (Kotlin/Android)
Swap callback hell for sexy suspend!
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:
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:
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 :)
Dependencies
Further Reading & Resources
Refs & Credits
- Existing 3-function callback to Kotlin Coroutines (Roman Elizarov)
- Generic function to wrap callbacks with coroutines (rwhite226)
- 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.