RxJava|RxAndroid 逐项加载

RxJava|RxAndroid load items one by one

有一个类别列表(A、B、C),每个列表都有一个子类别列表(A1、A2)、(B1、B2)、(C1、C2),每个子类别都有一个子类别列表要下载的项目 (item_a11、item_a12)、(item_a21、item_a22)、(item_b11、item_b12) 等等。所以,我需要按照以下顺序一个一个地加载项目:

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

是否可以使用RxJava实现?如果是这样,我将非常感谢任何建议!

你可以这样做

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.

假设您的 类 相似,您可以尝试此解决方案。它正在一项一项地下载项目,如果没有 space,则会抛出异常,因此不会进行进一步的下载尝试。

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 -> {});
}