Rxjava:也许平面图可以完成

时间:2018-10-13 04:43:52

标签: java rx-java

我正在使用具有两个函数的外部API,一个返回一个Maybe,另一个返回一个Completable(请参见下面的代码)。我希望我的函数'saveUser()'返回一个 Completable ,以便我可以使用doOnSuccess()doOnError进行检查。但是目前我的代码无法编译。另外请注意,如果我的'getMaybe'不返回任何内容,我想在我的平面图中获取一个空值作为参数,以便我可以处理空和非空情况(如代码所示)

    private Maybe<DataSnapshot> getMaybe(String key) {
        // external API that returns a maybe
    }

    private Completable updateChildren(mDatabase, childUpdates) {
        // external API that returns a Completable
    }

    // I'd like my function to return a Completable but it doesn't compile now
    public Completable saveUser(String userKey, User user) {
        return get(userKey)
                .flatMap(a -> {
                    Map<String, Object> childUpdates = new HashMap<>();

                    if (a != null) {
                        // add some key/values to childUpdates
                    }

                    childUpdates.put(DB_USERS + "/" + userKey, user.toMap());

                    // this returns a Completable
                    return updateChildren(mDatabase, childUpdates)
                });
    }

2 个答案:

答案 0 :(得分:3)

首先,请记住Maybe用于获取一个元素,为空或错误 我在下面重构您的代码,使posible返回Completable

public Completable saveUser(String userKey, User user) {
    return getMaybe(userKey)
            .defaultEmpty(new DataSnapshot)
            .flatMapCompletable(data -> {
                Map<String, Object> childUpdates = new HashMap<>();

                //Thanks to defaultempty the object has an 
                //Id is null (it can be any attribute that works for you) 
                //so we can use it to validate if the maybe method
                //returned empty or not
                if (data.getId() == null) {
                    // set values to the data
                    // perhaps like this
                    data.setId(userKey);
                    // and do whatever you what with childUpdates
                }

                childUpdates.put(DB_USERS + "/" + userKey, user.toMap());

                // this returns a Completable
                return updateChildren(mDatabase, childUpdates);
            });
}

答案 1 :(得分:1)

这是我最终想出的解决方案。

    public Completable saveUser(String userKey, User user) {
        return getMaybe(userKey)
                .map(tripListSnapshot -> {
                    Map<String, Object> childUpdates = new HashMap<>();
                    // // add some key/values to childUpdates
                    return childUpdates;
                })
                .defaultIfEmpty(new HashMap<>())
                .flatMapCompletable(childUpdates -> {
                    childUpdates.put(DB_USERS + "/" + userKey, user.toMap());
                    return updateChildren(mDatabase, childUpdates);
                });
    }