Returning combined Observable only if a condition matches
<p>Consider the following set and object:</p>
<pre><code>Observable.from(users); // Where users = List&lt;User&gt; and each user has a userId
Observable.just(location); // Where location has id, userId, coordinates
</code></pre>
<p>What I would like to do is iterate over the list of users, and upon the first encounter where <code>location.userId.equals(user.userId);</code> is queried in a database, return a combined object. If <code>userId</code>s do not match move to the next user. And terminate the loop once 1 match is found.</p>
<p>How can I achieve this with RxJava?</p>
<p>I initially thought to use:</p>
<pre><code>Observable.zip(Observable.from(users), Observable.just(location), new Func2&lt;User, Location, UserLocation&gt;() { ... });`
</code></pre>
<p>Does anyone have a better alternative?</p>
<h3>Edit:</h3>
<p>I thought maybe I could solve this with a simple solution, but alright I'll explain everything more clearly.</p>
<p>So once I have <code>location.userId</code>, and <code>user.userId</code> I need to also query a database which will return an <code>Observable&lt;Boolean&gt;</code> indicating whether it is also true in our database. If that condition matches then I return a combined object.</p>
<p>So the entire flow looks like this:</p>
<pre><code>for each user in Users {
    checkIfAlreadyExistsInDatabase(user.userId, location.userId) // Returns Observable&lt;Boolean&gt;

    // If exists in db AND user.userId == location.userId return combined object and terminate the loop
}
</code></pre>
<p>This was previously being done synchronously without <code>RxJava</code> I converted the method <code>checkIfAlreadyExistsInDatabase</code> to Rx and use <code>Schedulers.io</code> to ping the database on a background thread to make the app more response. The issue came up when I had to iterate over an array of Users and match the id with Location AND also ping my database.</p>
<p>In order for me to call the method <code>checkIfAlreadyExistsInDatabase</code> I need to grab a <code>user.userId</code> and to do that I need to iterate over <code>users</code> and filter with <code>location.userId</code>.</p>
<p>So:</p>
<ol>
<li>Iterate over users</li>
<li>If user.userId matches location.userId check if it exists in database</li>
<li>If exists in database return a combined object</li>
<li>Terminate loop once 1 match is found</li>
</ol>