我正在为RxJava2奋斗。我想对列表的每个项目执行功能。此功能:
public void function(final Result result) {
FirebaseFirestore.getInstance().collection(COLLECTION_NAME).document(result.getId()).get().addOnSuccessListener(new OnSuccessListener<DocumentSnapshot>() {
@Override
public void onSuccess(DocumentSnapshot documentSnapshot) {
// do some operation
}
});
}
此功能是异步的,并使用FirebaseFirestore。
因此,我尝试使用列表上的RxJava2来为每个项目调用该函数:
Observable.fromIterable(resultList)
.concatMap(result -> Observable.fromCallable(new Callable<String>() {
@Override
public String call() throws Exception {
function(result);
return "ok";
}
}))
.subscribe(r -> {
// do some operation when all firebase async tasks are done
});
concatMap起作用,并且为列表的每个项目调用该函数。问题是当完成所有Firebase异步任务时,我需要回调。
任何帮助将不胜感激。
答案 0 :(得分:1)
我将尝试画一个可能的解决方案:
public class Callback implements OnSuccessListener<DocumentSnapshot> {
private final ObservableEmitter<DocumentSnapshot> emitter;
private final boolean last;
public Callback(boolean lastvalue, ObservableEmitter<DocumentSnapshot> e) {
this.last = lastvalue;
this.emitter = e;
}
@Override
public void onSuccess(DocumentSnapshot value) {
emitter.onNext(value);
if (last) {
emitter.onComplete();
}
}
}
Observable<DocumentSnapshot> observable = Observable.create(new ObservableOnSubscribe<DocumentSnapshot>() {
@Override
public void subscribe(ObservableEmitter<DocumentSnapshot> e) throws Exception {
int i = 1;
for (Result result : resultList) {
/* callback object now knows which is the last request so it can emit the onComplete */
Callback callbackInstance = new Callback(resultList.size() == i, e);
i++;
FirebaseFirestore.getInstance().collection(COLLECTION_NAME)
.document(result.getId()).get().addOnSuccessListener(callbackInstance);
}
}
});
然后,当订阅者的onComplete
动作被点击时,对Firebase的所有请求都应完成。