Wrapping third-party callback-style APIs with coroutines
Often third-party libraries offer callback-style asynchronous APIs. However, the callback functions are considered to be an anti-pattern, especially whenever we are dealing with a number of nested callbacks. In this recipe, we are going to learn how to deal with libraries that provide callback-style methods by transforming them easily into suspending functions that can be run using coroutines.
Getting ready
The first step to start working with Kotlin Coroutines is to add the core framework dependency to the project:
implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-core:0.23.3'
The preceding code declares the kotlinx-coroutines-core
dependency in a Gradle build script, which is used in the sample project (https://github.com/PacktPublishing/Kotlin-Standard-Library-Cookbook).
As far as the recipe task is concerned, let's assume we have a class called Result
, defined as follows:
data class Result(val displayName: String)
Here is the...