Guest User

Untitled

a guest
Jan 7th, 2019
78
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Kotlin 1.50 KB | None | 0 0
  1. data class Author(val id: Int,
  2.                   val books: List<Int>)
  3.  
  4. data class Book(val id: Int,
  5.                 val author: Int,
  6.                 val title: String)
  7.  
  8. interface HttpClient {
  9.     // All methods here can throw an IOException.
  10.  
  11.     suspend fun getAuthor(id: Int): Author
  12.  
  13.     suspend fun getBook(id: Int): Book
  14. }
  15.  
  16. data class AuthorBooks(val author: Int,
  17.                        val books: List<Book>)
  18.  
  19. // Given a list of author ids, return a list of pairs (Author id, List<Book>). The list of authors should be processed
  20. // sequentially (i.e. one by one), but fetching all books from a given author should be done in parallel. In case of
  21. // error, return the sub list of (Author ID, List<Book>) that was computed successfully before the error occurred.
  22. suspend fun getAuthorBooks(authors: List<Int>): List<AuthorBooks> {
  23.     val httpClient: HttpClient = TODO() // get that from somewhere.
  24.  
  25.     val result = arrayListOf<AuthorBooks>()
  26.     try {
  27.         for (authorId in authors) {
  28.             val author = httpClient.getAuthor(authorId)
  29.             coroutineScope {
  30.                 val booksAsyncJobs: List<Deferred<Book>> = author.books.map { bookId ->
  31.                     async { httpClient.getBook(bookId) }
  32.                 }
  33.                 val books = booksAsyncJobs.map { it.await() }
  34.                 result.add(AuthorBooks(authorId, books))
  35.             }
  36.         }
  37.     } catch (e: Exception) {
  38.         // log, handle better.
  39.     } finally {
  40.         return result
  41.     }
  42. }
Advertisement
Add Comment
Please, Sign In to add comment