我正在使用值列表创建一个Observable列表,foreach值是一个自定义Observable.我全部使用merge运行它们,但是我无法检测到哪个触发onNext()或onError()
就像下面的代码:
List<Observable<MyhttpRsObj>> observables = new ArrayList<>(); for (String param : paramsList) { Observable<MyhttpRsObj> objObservable = MyRestClIEnt.get().dohttpRequest(param); observables.add(fileUploadobservable); } Observable<BaseRs> combinedobservables = Observable.merge(observables); combinedobservables.observeOn(AndroIDSchedulers.mainThread()) .subscribeOn(Schedulers.io()) .subscribe(new Subscriber<MyhttpRsObj>() { @OverrIDe public voID onCompleted() { //called only once when all Observables finished } @OverrIDe public voID one rror(Throwable throwable) { //how to kNow which Observable has error (which param) } @OverrIDe public voID onNext(MyhttpRsObj myhttpRsObj) { //how to kNow which Observable has sccess (which param) } });
解决方法:
由于将所有可观察值合并为一个,因此无法知道哪个可观察值触发了错误.
最好的选择是为每个可观察对象使用一个观察者.最后一个用于合并的Observable.
像这样:
List<Observable<MyhttpRsObj>> observables = new ArrayList<>(); for (String param : paramsList) { //change to connectable Observable ConnectableObservable<MyhttpRsObj> objObservable = MyRestClIEnt.get() .dohttpRequest(param) .publish(); //don't forget to connect observable.connect(); observables.add(fileUploadobservable); //subscribe for each observable objObservable.observeOn(AndroIDSchedulers.mainThread()) .subscribeOn(Schedulers.io()) .subscribe(new Subscriber<MyhttpRsObj>() { @OverrIDe public voID onCompleted() { //just partial completed } @OverrIDe public voID one rror(Throwable throwable) { //you can access param from here } @OverrIDe public voID onNext(MyhttpRsObj myhttpRsObj) { //access onNext here //you can access param from here } }); } Observable<BaseRs> combinedobservables = Observable.merge(observables); combinedobservables.observeOn(AndroIDSchedulers.mainThread()) .subscribeOn(Schedulers.io()) .subscribe(new Subscriber<MyhttpRsObj>() { @OverrIDe public voID onCompleted() { //called only once when all Observables finished } @OverrIDe public voID one rror(Throwable throwable) { //don't handle error here } @OverrIDe public voID onNext(MyhttpRsObj myhttpRsObj) { } });
PS:使用ConnectableObservable避免发射两次
总结以上是内存溢出为你收集整理的java-Observable merge()检测触发了哪个observable全部内容,希望文章能够帮你解决java-Observable merge()检测触发了哪个observable所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)