FlatMapIterable和空列表

时间:2017-04-05 19:37:38

标签: android rx-java2

我想使用RxJava 2对来自数据库的一组项目执行后台任务。项目列表可能为空,这意味着我不能使用flatMapIterable,因为它会在空列表上抛出异常:

    Observable
            .fromCallable(() -> SQLite
                        .select()
                        .from(VideoUpload.class)
                        .where(VideoUpload_Table.status.eq(VIDEO_UPLOAD_IN_PROGRESS))
                        .queryList())
            .flatMapIterable(videoUploads -> videoUploads)
            .map(videoUpload -> {
                videoUpload.setStatus(VIDEO_UPLOAD_NOT_STARTED);
                return videoUpload;
            })
            .firstElement()
            .subscribeOn(Schedulers.io())
            .subscribe(/* TODO */);

我可以将所有内容移动到callable中,在那里进行过滤等等,但我认为根据上面的代码可能会有更优雅的解决方案。

1 个答案:

答案 0 :(得分:0)

事实证明flatMapIterable不会在RxJava-2上抛出异常,我记得它在RxJava-1上抛出异常。无论如何,这样做的方法如下

    Observable
            .fromCallable(() -> {
                List<VideoUpload> videos = SQLite
                        .select()
                        .from(VideoUpload.class)
                        .where(VideoUpload_Table.status.in(VIDEO_UPLOAD_IN_PROGRESS, VIDEO_UPLOAD_QUEUED))
                        .queryList();
                return videos;
            })
            .flatMapIterable(videoUploads -> videoUploads)
            .map(videoUpload -> {
                videoUpload.setStatus(VIDEO_UPLOAD_NOT_STARTED);
                return videoUpload;
            })
            .firstElement()
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(/* TODO */);