如何使用retrofit和rxjava调用n次休息服务并在结尾解释结果?

时间:2018-03-02 04:00:05

标签: android retrofit2

我试图在调用n次休息服务后处理结果,但是一个属性告诉我是否要调用Web服务的对象列表,但是当完成n时我无法处理最终结果调用,似乎是由于异步,有人能告诉我我做错了什么吗?非常感谢,并原谅我的英语不好。

示例代码为:

private List<ResquestService> request;

private void process(){
    Observable.fromIterable(request)
    .filter(resquestService -> resquestService.getType().equals(WS_TYPE))
    .observeOn(AndroidSchedulers.mainThread())
    .subscribeOn(Schedulers.newThread())
    .subscribe(
            resquestService -> {consumeRestService(resquestService);},
            Throwable::printStackTrace,
            () -> {processFinalResults();}
    );
}

private void consumeRestService(ResquestService resquestService){
    getApi().processData(resquestService)
            .observeOn(AndroidSchedulers.mainThread())
            .subscribeOn(Schedulers.newThread())
            .subscribe(
                    next -> {processResultWS();},
                    error -> {handleErrorWS();}
            );
}

public class ResquestService {
    private int id;
    private String name;
    private String type;
}

1 个答案:

答案 0 :(得分:0)

解决方案是放入可迭代的 .subscribeOn(Schedulers.newThread())

并且在休息服务的呼叫中: .observeOn(AndroidSchedulers.mainThread())

private void process(){
    Observable.fromIterable(request)
    .filter(resquestService -> resquestService.getType().equals(WS_TYPE))
    .subscribeOn(Schedulers.newThread())
    .subscribe(
            resquestService -> {consumeRestService(resquestService);},
            Throwable::printStackTrace,
            () -> {processFinalResults();}
    );
}

private void consumeRestService(ResquestService resquestService){
    getApi().processData(resquestService)
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(
                    next -> {processResultWS();},
                    error -> {handleErrorWS();}
            );
}