3

I want to make a HTTP request repeatedly and act on result. I start with public Observable<NewsItem> fetchItems(NewsFeed feed). One request gets a few news items but I decided to flatten it.

The idea was to use Observable.interval() make the request multiple times, then combine resulting Observables into one.

       Observable
            .interval(timePerItem, TimeUnit.MILLISECONDS)
            .map(i -> feed)
            .map(feed -> fetchItems(feed))
            .subscribe(result -> System.out.println(result));

But the result is Observable<Observable<NewsItem>> not Observable<NewsItem>. How to marge them?

I have found the marge() operator (RX-Java doc: Marge). But it does not seem to fit the use case.

In previous version I used CompletableFuture<List<NewsItem>> fetchNewsItems() but I wasn't able to fit it into Observable chain.

1 Answer 1

3

Not sure if I understand the problem, but aren't you just looking for flatMap?

Observable
    .interval(timePerItem, TimeUnit.MILLISECONDS)
    .flatMap(i -> fetchItems(feed))
    .subscribe(result -> System.out.println(result));
Sign up to request clarification or add additional context in comments.

2 Comments

Looks like that is what I was looking for. Learning rx-java from github.com/ReactiveX/RxJava/wiki is hard. flatMap is not mentioned in the introduction and the way it is described in github.com/ReactiveX/RxJava/wiki/… is strange. Thank you!
There are many more links to great tutorials at reactivex.io/tutorials.html. And if you find a good tutorial which is not yet mentioned there or you wrote one yourself, make a pull request at github.com/ReactiveX/reactivex.github.io so that the link is included on that page ;-)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.