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

66 Views Asked by At

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?

1

There are 1 best solutions below

1
On BEST ANSWER

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.