使用RxJava和Android进行多个API调用

时间:2017-02-03 07:12:21

标签: android api rx-java

我有一个对象列表,这些对象应按顺序传递给API,并在完成所有调用后需要最终回调。代码结构看起来像

//Singleton class
public class RestAPIManager {

    public Completable doSomething(A a) {
        //Make API call here and return Completeable
    }
}

//Class from which the above API call is made
public class FragmentA extends Fragment {
    List<A> aList = new ArrayList<A>;

    //This method should return completable after all calls are made
    private Completable callDoSomething(List<A> data) {
        // The code that I tried
        Observable.just(data)
            .flatMap(new <List<A>, Observable<?>>() {
                @Override
                public Observable<?> call(List<A> dataList) {
                    //WHAT SHOULD BE RETURNED FROM HERE
                    for (A a : dataList) {
                        RestAPIManager.getInstance().doSomething(a)    
                    }
                }
            })
            .doOnCompleted(new Action0() {
                @Override
                public void call() {

                }
            })
            .doOnError(new Action1<Throwable>() {
                @Override
                public void call(Throwable throwable) {

                }
            })
            .toCompletable(); 
    }
}

我刚刚开始使用RxJava,所以我真的不确定如何继续使用它。

2 个答案:

答案 0 :(得分:1)

您可以使用from运算符展平列表,然后concatMap按顺序处理每个项目:

Observable.from(data)
    .concatMap(new Func1<A, Observable<?>>() {
        @Override
        public Observable<?> call(A a) {
            return RestAPIManager.getInstance().doSomething(a);
        }
    })
    .toCompletable();

答案 1 :(得分:0)

对于Android使用类似这样的东西

public void doIt(List<String> data) {
    final Subscription subscription = proceed(data)
            .subscribe(new Subscriber<List<String>>() {
                @Override
                public void onCompleted() {
                    //final callback here
                    System.out.println("on completed");
                }

                @Override
                public void onError(Throwable e) {
                    //invokes on error
                    System.out.println("on error");
                }

                @Override
                public void onNext(List<String> strings) {
                    //invokes on items emits
                    strings.forEach(System.out::print);
                }
            });
}

private Observable<List<String>> proceed(List<String> data) {
    return Observable.from(data)
            .map(RestApiManager.getInstance()::doSomething)
            .toList();
}

并通过subscription.unsubscribe()取消订阅请求执行;当onStop()调用以避免泄漏时。不要忘记调度程序