title: RxJava2 combine multiple observables to make them return single result
body: <p>How to combine multiple results emmited by observables into one result and emit it once?</p>
  
  <p>I have a Retrofit service:</p>
  
  <pre><code>public interface MyService {
  
      @GET("url")
      Observable&lt;UserPostsResult&gt; getUserPosts(@Query("userId") int id);
  
      @GET("url")
      Observable&lt;UserPostsResult&gt; getUserPosts(@Query("userId") int id, @Query("page") int pageId);
  }
  </code></pre>
  
  <p>And I have a model:</p>
  
  <pre><code>public class UserPostsResult {
  
     @SerializedName("posts")
     List&lt;UserPost&gt; mPosts;
  
     @SerializedName("nextPage")
     int mPageId;
  }
  </code></pre>
  
  <p>Also I have ids <code>List&lt;Integer&gt; friendsIds;</code></p>
  
  <p>My goal is to have a method like this one:</p>
  
  <pre><code>public Observable&lt;Feed&gt; /*or Single&lt;Feed&gt;*/ getFeed(List&lt;Integer&gt; ids) {
      ...
  }
  </code></pre>
  
  <p>It returns one <code>Observable</code> or <code>Single</code> that does the following:</p>
  
  <ul>
  <li>Combines all <code>getUserPosts(idFromList)</code> to one observable</li>
  <li><p>For each <code>UserPostsResult</code> must do:</p>
  
  <p><code>if (userPostResult.mPageId &gt; -1) 
      getUserPosts(currentUserId, userPostResult.mPageId);</code></p>
  
  <p>And merge this result to the previous <code>userPostResult</code></p></li>
  <li><p>Return one single model as result of all operations.</p></li>
  </ul>
  
  <p>Result class:</p>
  
  <pre><code>public class Feed {
      List&lt;UserPost&gt; mAllPostsForEachUser;
  }
  </code></pre>
  
  <p><strong>EDIT (More details):</strong></p>
  
  <p>My client specifications was that I must take from social network user posts with no logging in, no token requesting. So I must parse HTML pages. That's why I have this complex structure.</p>
  
  <p><strong>EDIT (Partial solution)</strong></p>
  
  <pre><code>public Single&lt;List&lt;Post&gt;&gt; getFeed(List&lt;User&gt; users) {
      return Observable.fromIterable(users)
              .flatMap(user-&gt; mService.getUserPosts(user.getId())
                      .flatMap(Observable::fromIterable))
              .toList()
              .doOnSuccess(list -&gt; Collections.sort(list, (o1, o2) -&gt;
                      Long.compare(o1.getTimestamp(), o2.getTimestamp())
              ));
  }
  </code></pre>
  
  <p>This solution doesn't include pages problem. Thats why it is only partial solution</p>