2017-09-14 63 views
0

有一個類別列表(A,B,C),每個列表都有一個子類別列表(A1,A2),(B1,B2),(C1,C2)和每個子類別都有一個要下載的項目列表(item_a11,item_a12),(item_a21,item_a22),(item_b11,item_b12)等等。所以,我需要按以下順序逐個加載項目:RxJava | RxAndroid逐個加載項目

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實現?如果是這樣,我會非常感謝任何建議!

+0

子類別是在類別中加載還是需要額外的調用? – crgarridos

回答

0

假設你的類是相似的,你可以試試這個解決方案。它是一個接一個地下載項目,如果沒有空間,則拋出異常,因此不會再進行下載嘗試。

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

你可以做這樣的事情

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.