M Rajoy
M Rajoy

Reputation: 4074

RxJava to emit items one by one

I have a list of videos retrieved from a database using RxJava. I want to display these videos in a RecyclerViews and generate a thumbnail along the way. The problem is that the generation of thumbnails

Bitmap thumb = ThumbnailUtils.createVideoThumbnail(localVideo.getFilename(),
                    MediaStore.Images.Thumbnails.MINI_KIND);

is too slow so that when I have lots of videos on my list it blocks the loading of the screen.

What I would like to know is have my video list retrieved in a way that each item is emitted one by one instead of the list as a whole, and feed each item as it is done processing (generating the thumbnail) to the UI (maybe this approach is not even the right one).

This is my video loading code:

public void loadVideoList() {


        Subscriber<List<LocalVideo>> subscriber = new Subscriber<List<LocalVideo>>() {
            @Override
            public void onCompleted() {

            }

            @Override
            public void onError(Throwable e) {
                if (isViewAttached()) {
                    Timber.e("Error retrieving local videos", e);
                    getView().showError();
                }
            }

            @Override
            public void onNext(List<LocalVideo> videoList) {
                if (isViewAttached()) {
                    getView().showVideoList(videoList);
                    if(videoList.isEmpty()) {
                        getView().showNoVideos();
                    }
                }
            }
        };
        mStoredVideoRepository
                .getLocalVideos()
                .subscribeOn(mScheduleProvider.computation())
                .observeOn(mScheduleProvider.ui())
                .subscribe(subscriber);
        addToSubscriptions(subscriber);
    }

Upvotes: 0

Views: 2027

Answers (1)

akarnokd
akarnokd

Reputation: 69997

Use flatMapIterable to "unroll" an inner list:

Observable.fromCallable(() -> Arrays.asList(1, 2, 3, 4, 5, 6))
.subscribeOn(Schedulers.io())
.flatMapIterable(v -> v)
.observeOn(Schedulers.computation())
.map(v -> v * 2)
.observeOn(AndroidSchedulers.mainThread())
.subscribe(System.out::println);

Upvotes: 2

Related Questions