RxJava:使用Completable的Maybe flatMap

3
我正在使用一个外部API,其中有两个函数,一个返回Maybe,另一个返回Completable(请参见下面的代码)。我希望我的函数“saveUser()”返回一个Completable,这样我就可以使用doOnSuccess()doOnError来检查它。但目前我的代码无法编译。另外,请注意,如果我的“getMaybe”没有返回任何内容,则我希望在我的flatmap中获得一个null值作为参数,以便我可以处理null vs非null情况(如代码所示)。
    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)
                });
    }

1
你能把编译器错误放在问题里吗? - Sam Orozco
2个回答

3

首先,记住 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);
            });
}

2
这是我最终想出的解决方案。
    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);
                });
    }

实际上,defaultIfEmpty 是检查 "map" 是否返回了 "childUpdates",而不是检查 getMaybe() 是否获取了空值。 - dmarquina

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接