CamilleBC
06/26/2019, 2:31 PMsuspend fun getChapters(chapterIds: List<String>): List<Chapter> =
mutableListOf<Chapter>().apply {
chapterIds.forEach { launch { add(getChapter(it)) } }
}
suspend fun getChapter(chapterId: String): Chapter {
val response = service.getChapter(chapterId)
return if (response.isSuccessful) {
val doc = Jsoup.parse(response.body()?.string())
Chapter(
doc.select(CHAPTER_TITLE_QUERY).text(),
doc.select(CHAPTER_CONTENT_QUERY).html().lines()
)
} else Chapter()
}
Dico
06/26/2019, 2:39 PMsuspend fun getChapters(chapterIds: List<String>): List<Deferred<Chapter>> = coroutineScope {
chapterIds.map {
async { getChapter(it) }
}
}
for (deferred in result) {
val chapter = deferred.getOrNull() ?: continue
// draw chapter, perhaps
}
result.map { it.await() }
which gives a List<Chapter>
once all downloads completedCamilleBC
06/26/2019, 2:44 PMmap,async
, and then the map.await() to return the list. That way, the person using my library won't have to do it himself. Thank you so much for the help !suspend fun getChapters(chapterIds: List<String>): List<Chapter> {
val deferredList : List<Deferred<Chapter>> = coroutineScope {
chapterIds.map { async { getChapter(it) } }
}
return deferredList.map { it.await() }
}
I think that does what I need.Dico
06/26/2019, 4:00 PMawait
in a try/catch and make the chapters perhaps nullable, or use mapNotNull
.
Failures may also cancel the coroutine and its parents, to avoid this use supervisorScope
instead of coroutineScope
CamilleBC
06/26/2019, 5:08 PM