Search code examples
kotlinrx-java2rx-kotlin

Transform Single<List<Maybe<Book>>> to Single<List<Book>>


could someone help, please?

I have these functions

fun getBooks(): Single<List<Book>> {
    return getCollections()
        .map {
            it.map(::collectonToBook)
        }
}

fun getCollections(): Single<List<Collection>> {
   return db.fetchCollections()
       .filter(::isBook)
}

fun collectonToBook(collection: Collection): Maybe<Book> {
    return collection.toBook()
}
            

The problem is getBooks returns Single<List<Maybe<Book>>> when I need Single<List<Book>>. Can I do that inside the stream without calling blockingGet?


Solution

  • Try this:

    getCollections()                        // Single<List<Collection>>
    .flattenAsFlowable { it }               // Flowable<Collection>
    .concatMapMaybe { collectonToBook(it) } // Flowable<Book>
    .toList()                               // Single<List<Book>>
    

    In words, unwrap the inner List into its elements, transform the Collection into a Book, concatenate their respective Maybe sources, then finally collect the Books into a List again.