Gorets Gorets - 11 days ago 8
Java Question

Filled model with extra response using Rx

I'm new with Rx java and my current task is I have 2 requests

@GET(NEWS_LIST)
fun getNews(): Observable<NewsResponse>

@GET
fun getNewsImage(@Url url: String): Observable<NewsImage>


and I'd want to add image url to 1st response model from 2nd one. 2nd one depends on 1st one. How is it possible to merge them in Rx stream?

So 1st request returns me list of news, then I need to call
getNewsImage(url)
for each item with url from this model, parse real image url from second response, add it to
news
object and get final list with filled models
Thanks for any advice

Answer
getNews()
        .flatMap { Observable.fromIterable(it.getTopicsList()) } //or Observable.from() if you use RxJava1
        .flatMap({ getNewsImage(it) }, { topic, imageUrl ->
            topic.imageUrl = imageUrl
            return@flatMap topic
        })
        .toList()

Second flatMap combines items from the source Observable with the Observable triggered by those source items, and emits these combinations. More info