Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- data class Author(val id: Int,
- val books: List<Int>)
- data class Book(val id: Int,
- val author: Int,
- val title: String)
- interface HttpClient {
- // All methods here can throw an IOException.
- suspend fun getAuthor(id: Int): Author
- suspend fun getBook(id: Int): Book
- }
- data class AuthorBooks(val author: Int,
- val books: List<Book>)
- // Given a list of author ids, return a list of pairs (Author id, List<Book>). The list of authors should be processed
- // sequentially (i.e. one by one), but fetching all books from a given author should be done in parallel. In case of
- // error, return the sub list of (Author ID, List<Book>) that was computed successfully before the error occurred.
- suspend fun getAuthorBooks(authors: List<Int>): List<AuthorBooks> {
- val httpClient: HttpClient = TODO() // get that from somewhere.
- val result = arrayListOf<AuthorBooks>()
- try {
- for (authorId in authors) {
- val author = httpClient.getAuthor(authorId)
- coroutineScope {
- val booksAsyncJobs: List<Deferred<Book>> = author.books.map { bookId ->
- async { httpClient.getBook(bookId) }
- }
- val books = booksAsyncJobs.map { it.await() }
- result.add(AuthorBooks(authorId, books))
- }
- }
- } catch (e: Exception) {
- // log, handle better.
- } finally {
- return result
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment