java - Rxjava : Maybe flatmap with completable

标签 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)
                });
    }

最佳答案

首先,记住 Maybe 是用来获取一个元素,空或者错误 我重构了下面的代码,以便可以返回 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);
            });
}

关于java - Rxjava : Maybe flatmap with completable,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52789602/

相关文章:

java - 将 Spark 的 Kryo 序列化程序与具有字符串数组的 Java Protocol Buffer 一起使用时出错

java - 无法连接到我的 Derby 数据库

rx-java - 使用 repeatWhen() 的动态延迟值

android - 使用 Retrofit 和 RX-java 处理无网络的正确方法

java - RxJava groupBy 和后续阻塞操作(onComplete 缺失?)

android - RxJava 链请求和更新 UI

reactive-programming - 订阅时评估startwith的参数

java - 我该如何解析这个json?

java - 将 System.out.print 转换为 JOptionPane?

java - 从 .dat 文件中检索数据