Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- 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) }
- }
- .mapNotNull {
- // Will Throw an Exception when awaiting for id=8
- if (!it.isCompletedExceptionally) it.await() else null
- }
- }
- 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)
- }
- }
Add Comment
Please, Sign In to add comment