Guest User

Untitled

a guest
Sep 25th, 2018
102
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.12 KB | None | 0 0
  1. import kotlinx.coroutines.experimental.GlobalScope
  2. import kotlinx.coroutines.experimental.async
  3. import kotlinx.coroutines.experimental.runBlocking
  4. import java.util.*
  5.  
  6. data class GiftCard(val id: Int, val code: String)
  7.  
  8. class GiftCardService {
  9.  
  10. /**
  11. * Just plain Kotlin code, might throw an Exception
  12. *
  13. * In our case this would be a call to a RESTful service
  14. */
  15. fun getGiftCard(id: Int): GiftCard {
  16. println("Getting GiftCard with id: $id")
  17. if (id == 8) throw Exception("Boom!")
  18. return GiftCard(id = id, code = UUID.randomUUID().toString())
  19. }
  20.  
  21. /**
  22. * Async invoke getGiftCard() for the whole list of GiftCard ids
  23. *
  24. * Suspend keyword is mandatory due to the await() function call
  25. */
  26. suspend fun getGiftCards(): List<GiftCard> = listOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 0)
  27. .map {
  28. // Launch the Coroutine and returns immediately
  29. GlobalScope.async { getGiftCard(it) }
  30. }
  31. .map {
  32. // Will Throw an Exception when calling await() for id=8
  33. val await = it.await()
  34. println("Fetched GiftCard: $await")
  35. await
  36. }
  37.  
  38. /**
  39. * Async invoke getGiftCard() for the whole list of GiftCard ids, ignoring the failed ones.
  40. *
  41. * Suspend keyword is mandatory due to the await() function call
  42. */
  43. suspend fun getSuccessfullyFetchedGiftCards(): List<GiftCard> = listOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 0)
  44. .map {
  45. // Launch the coroutine and returns immediately
  46. GlobalScope.async { getGiftCard(it) }
  47. }
  48. .mapNotNull {
  49. // Will Throw an Exception when awaiting for id=8
  50. if (!it.isCompletedExceptionally) it.await() else null
  51. }
  52. }
  53.  
  54. fun main(args: Array<String>) = runBlocking {
  55. try {
  56. val giftCards = GiftCardService().getGiftCards() // Will throw an Exception
  57. } catch (e: Exception) {
  58. println("Shit exploded: ${e.message}")
  59. }
  60.  
  61. val giftCards = GiftCardService().getSuccessfullyFetchedGiftCards().forEach {
  62. println(it)
  63. }
  64. }
Add Comment
Please, Sign In to add comment