0

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?

mXaln
  • 105
  • 11

1 Answers1

4

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.

akarnokd
  • 69,132
  • 14
  • 157
  • 192
  • Wow! It works like a miracle, Thank you so much. And for quick response as well! Cheers! – mXaln Dec 09 '20 at 13:25