使用Rx和Retrofit过滤响应

时间:2016-10-17 22:22:08

标签: android retrofit rx-java

我在Rx中打电话是这样的:

rxHelper.manageSubscription(HavocService.getInstance().getHavocAPI().getAllTasks(userId)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .compose(RxTiPresenterUtils.deliverLatestToView(this))
                .subscribe(response -> {
                    this.mStandardTaskResponse = response;
                    mListOfTasks = mStandardTaskResponse.getTasks();
                    getView().setTaskList(mListOfTasks);
                    getView().setLoading(false);
                }, throwable -> {
                    getView().setLoading(false);
                    throwable.printStackTrace();
                })
        );

response属于以下类型

public class StandardTaskResponse {

    /**
     * Whether or not there was an error with the response
     */
    public boolean status;

    /**
     * List of Tasks
     */
    @SerializedName("doc")
    public List<Task> tasks;

    /**
     * Gets the array of Tasks from the response
     *
     * @return the List of Tasks
     */
    public List<Task> getTasks() {
        return tasks;
    }
}

我想过滤响应的任务列表。例如,我只希望列表包含例如TaskFromList.getStatus() == 2的项目。

如何使用Rx执行此操作?

1 个答案:

答案 0 :(得分:2)

这就是我最终做的事情

rxHelper.manageSubscription(HavocService.getInstance().getHavocAPI().getAllTasks(USER)
                .flatMap(response -> Observable.from(response.getTasks()))
                //filter out Tasks that are ARCHIVED or DONE
                .filter(task -> task.getStatus() == TaskStatusEnum.INCOMPLETE)
                .toList()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .compose(RxTiPresenterUtils.deliverLatestToView(this))
                .subscribe(list -> {
                    mListOfTasks = list;
                    getView().setTaskList(mListOfTasks);
                    getView().setLoading(false);
                }, throwable -> {
                    getView().setLoading(false);
                    throwable.printStackTrace();
                })
        );