仅在条件匹配时才返回组合的Observable

And*_*oid 6 android operators rx-java

考虑以下集合和对象:

Observable.from(users); // Where users = List<User> and each user has a userId
Observable.just(location); // Where location has id, userId, coordinates
Run Code Online (Sandbox Code Playgroud)

我想要做的是迭代用户列表,并在第一次遇到location.userId.equals(user.userId);数据库中查询的地方时,返回一个组合对象.如果userIds不匹配则移动到下一个用户.并在找到1匹配后终止循环.

我怎样才能用RxJava实现这个目标?

我最初想过要用:

Observable.zip(Observable.from(users), Observable.just(location), new Func2<User, Location, UserLocation>() { ... });`
Run Code Online (Sandbox Code Playgroud)

有没有人有更好的选择?

编辑:

我想也许我可以用一个简单的解决方案解决这个问题,但好吧我会更清楚地解释一切.

所以,一旦我拥有location.userId,user.userId我还需要查询一个数据库,该数据库将返回一个Observable<Boolean>指示它是否也在我们的数据库中为真的数据库.如果该条件匹配,那么我返回一个组合对象.

所以整个流程看起来像这样:

for each user in Users {
    checkIfAlreadyExistsInDatabase(user.userId, location.userId) // Returns Observable<Boolean>

    // If exists in db AND user.userId == location.userId return combined object and terminate the loop
}
Run Code Online (Sandbox Code Playgroud)

这是以前同步完成的,RxJava我没有将方法转换checkIfAlreadyExistsInDatabase为Rx并用于Schedulers.io在后台线程上ping数据库以使应用程序更具响应性.当我不得不迭代一组用户并将id与Location AND匹配并且ping我的数据库时,问题出现了.

为了让我调用方法,checkIfAlreadyExistsInDatabase我需要抓住一个user.userId并做到这一点,我需要迭代users并过滤location.userId.

所以:

  1. 迭代用户
  2. 如果user.userId与location.userId匹配,请检查它是否存在于数据库中
  3. 如果存在于数据库中则返回组合对象
  4. 找到1匹配后终止循环

R. *_*ski 2

函数的问题zip在于它从左侧发出一项Observable,从右侧发出一项Observable。因此,您提供的函数将仅对第一个用户执行。但这是一个好的方向。只需重复第二次Observable适量使用即可repeat。如果您确实想使用 RxJava 来执行此操作,建议的方法如下:

Observable.zip(Observable.from(userList),
        Observable.just(location).repeat(userList.size()),
        new Func2<User, Location, User>() {
            @Override
            public User call(User user, Location location) {
                return user.id.equals(location.id) ? user : null;
            }
        })
        .filter(new Func1<User, Boolean>() {
            @Override
            public Boolean call(User user) {
                return user != null;
            }
        });
Run Code Online (Sandbox Code Playgroud)

然而,这种方法null是通过流传递的Observable,不推荐这样做。

我不会使用 RxJava 来做到这一点,而只会使用传统的 Java 的Iterator.