July 2018
Intermediate to advanced
400 pages
12h 14m
English
One way to create a coroutine is to use the async function provided with the coroutine library. The async function requires one argument: a lambda that specifies the work you want to happen in the background.
In fetchCharacterData, move the blocking readText function call into a lambda and pass it to the async function. Also, update the return type to be a Deferred<CharacterGenerator.CharacterData>, the result of the async function:
Listing 22.7 Making fetchCharacterData async (CharacterGenerator.kt)
...
fun fetchCharacterData(): Deferred<CharacterGenerator.CharacterData> {
return async {
val apiData = URL(CHARACTER_DATA_API).readText()
return CharacterGenerator.fromAPIData(apiData)
} } ...Read now
Unlock full access