简体   繁体   English

如何在 RxJava 中执行链式任务?

[英]How to perform chain tasks in RxJava?

I want to perform tasks in RxJava one by one.我想一一执行 RxJava 中的任务。
For Example:-例如:-
1. Fetch User Ids from Server 1.从服务器获取用户 ID
2. Fetch Users from server by thier Ids. 2.通过他们的ID从服务器获取用户。

I have tried this method我试过这个方法

public Observable<List> getUids(){ return Observable.create(emitter -> { List<String> uids = new ArrayList<>(); //fetchData from server emitter.onNext(uids); }); } public Observable<User> getUser(String uid){ return Observable.create(emitter -> { User user = new User(); //fetchData user from server emitter.onNext(user); }); } //Executing this code like getUids().flatMapIterable(ids -> ids) .flatMap(this::getUser) .subscribe(new Observer<User>() { @Override public void onSubscribe(Disposable d) { } @Override public void onNext(User user) { print("next "+user.getName()); } @Override public void onError(Throwable e) { print("error "+e.getMessage()); } @Override public void onComplete() { print("complete"); } });

There are some problems in it里面有一些问题
1.this is not calling Subscriber's onComplete() method when all users are fetched. 1.这不是在获取所有用户时调用订阅者的onComplete()方法。
2.if there is an error in getUser method, app is crashing. 2.如果getUser方法有错误,app就崩溃了。 with io.reactivex.exceptions.UndeliverableException exception io.reactivex.exceptions.UndeliverableException异常

Can you please tell me where I am mistaking?你能告诉我我错在哪里吗?

  1. Call emitter.onComplete() in your getUids() and getUser(...) Observables and then append .toList() after .flatMap(this::getUser) .getUids()getUser(...) Observables 中调用emitter.onComplete() ,然后在.flatMap(this::getUser)之后附加.toList() .flatMap(this::getUser)

    Returns a Single that emits a single item, a list composed of all the items emitted by the finite source ObservableSource.返回一个发出单个项目的 Single,一个由有限源 ObservableSource 发出的所有项目组成的列表。

  2. UndeliverableException is a wrapper for the exception that is happening in your .flatMap(this::getUser) . UndeliverableException.flatMap(this::getUser)发生的异常的包装器。 I can not help you more with the information that you provided, what is it that you want to happen when an exception is thrown?对于您提供的信息,我无法为您提供更多帮助,抛出异常时您希望发生什么?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM