Skip to content

Instantly share code, notes, and snippets.

@soudmaijer
Last active September 26, 2018 11:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save soudmaijer/24478d2509a1d95b42018d5ac51b1ec6 to your computer and use it in GitHub Desktop.
Save soudmaijer/24478d2509a1d95b42018d5ac51b1ec6 to your computer and use it in GitHub Desktop.
Using Kotlin Coroutines to async fetch data from an external service
import kotlinx.coroutines.experimental.GlobalScope
import kotlinx.coroutines.experimental.async
import kotlinx.coroutines.experimental.runBlocking
import java.util.*
data class GiftCard(val id: Int, val code: String)
class GiftCardService {
/**
* Just plain Kotlin code, might throw an Exception
*
* In our case this would be a call to a RESTful service
*/
fun getGiftCard(id: Int): GiftCard {
println("Getting GiftCard with id: $id")
if (id == 8) throw Exception("Boom!")
return GiftCard(id = id, code = UUID.randomUUID().toString())
}
/**
* Async invoke getGiftCard() for the whole list of GiftCard ids
*
* Suspend keyword is mandatory due to the await() function call
*/
suspend fun getGiftCards(): List<GiftCard> = listOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 0)
.map {
// Launch the Coroutine and returns immediately
GlobalScope.async { getGiftCard(it) }
}
.map {
// Will Throw an Exception when calling await() for id=8
val await = it.await()
println("Fetched GiftCard: $await")
await
}
/**
* Async invoke getGiftCard() for the whole list of GiftCard ids, ignoring the failed ones.
*
* Suspend keyword is mandatory due to the await() function call
*/
suspend fun getSuccessfullyFetchedGiftCards(): List<GiftCard> = listOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 0)
.map {
// Launch the coroutine and returns immediately
GlobalScope.async { getGiftCard(it) }
}
.filter { !it.isCompletedExceptionally }
.map { it.await() }
}
fun main(args: Array<String>) = runBlocking {
try {
val giftCards = GiftCardService().getGiftCards() // Will throw an Exception
} catch (e: Exception) {
println("Shit exploded: ${e.message}")
}
val giftCards = GiftCardService().getSuccessfullyFetchedGiftCards().forEach {
println(it)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment