Andy F
Andy F

Reputation: 3

RxJava|RxAndroid load items one by one

There is a list of categories (A, B, C) and each list has a list of subcategories (A1, A2), (B1, B2), (C1, C2) and each subcategory has a list of items to download (item_a11, item_a12), (item_a21, item_a22), (item_b11, item_b12) and so on. So, I need load items one by one in the following order:

Loading category A
...Loading subcategory A1
......Loading item_a11 - check if we still have free space
......Loading item a12 - check if we still have free space
...Loading subcategory A2
......Loading item_a12 - check if we still have free space
......Loading item a12 - check if we still have free space - no space
Download Completed

Is it possible to implement using RxJava? If so I'll be very thankful for any advice!

Upvotes: 0

Views: 353

Answers (2)

Aleksander Mielczarek
Aleksander Mielczarek

Reputation: 2825

Assuming that your classes are similar, you can try this solution. It is downloading items one by one and in case of no space, exception is thrown, so no further download attempts will be taken.

public interface Model {

    Single<String> download(String item);

    Single<List<Category>> categories();

    Single<Boolean> availableSpace();
}


public class Category {

    public List<Subcategory> subcategories;

    public List<Subcategory> getSubcategories() {
        return subcategories;
    }
}

public class Subcategory {

    public List<String> items;

    public List<String> getItems() {
        return items;
    }
}


private Model model;

public void downloadAll() {
    model.categories()
            .flatMapObservable(Observable::fromIterable)
            .map(Category::getSubcategories)
            .flatMap(Observable::fromIterable)
            .map(Subcategory::getItems)
            .flatMap(Observable::fromIterable)
            .flatMapSingle(item -> model.availableSpace()
                    .flatMap(available -> {
                        if (available) {
                            return model.download(item);
                        } else {
                            return Single.error(new IllegalStateException("not enough space"));
                        }
                    }))
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(item -> {}, throwable -> {});
}

Upvotes: 0

Deep Naik
Deep Naik

Reputation: 491

you can do something like this

1)make method that returns List of A(getListOfA).
2)now getListofA.subscribe().
3)now on onNext() call getListOfA1() that return single value using fromIterable()(i.e. return single item from A1.
4)now on getListofA1().subscribe()'s onNext you can do what you want.

Upvotes: 0

Related Questions