我使用的外部 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/