2016-11-30 71 views
1

說我有那些過於類如何加載relationed對象與RxJava

class Event { 
    int id; 
    String name; 
    List<Integer> facilityIds; 
    List<Facility> facilities; // Empty, the one I need to load 
} 

class Facility { 
    int id; 
    String name; 
} 

目標:打印出他們的設施的名稱每個事件。

約束RxJava2,設施只能由一個(getFacility(facilityId)

加載一個從Observable<Event>,我無法找到我的路周圍裝載設施,並設置他們回到各自的活動。

基本上我在想是這樣的:

Observable<Event> events; 
events 
    .map(Event::getFacilityIds) 
    .flatMap(Observable::fromIterable) 
    .map(facilityId -> service.getFacility(facilityId)) 
    . // somehow get the event reference and 
    // so some event.addFacility() or something similar 

然後我去相親,不能找到一種方法將它們鏈接回事件。我也想過使用zip,它可能是一個解決方案,但我沒有找到一種方法來保存和事件引用,以便稍後將設施設置給他們。

什麼是被動的方式去?任何提示將不勝感激。

回答

2

怎麼樣forEach?

events.forEach(event -> Observable.fromIterable(event.facilityIds) 
      //or just .map(service::getFacility) 
      .map(facilityId -> service.getFacility(facilityId) 
      .forEach(facility -> event.facilities.add(facility))) 

或者使用doOnNext代替第一forEach如果你想繼續 流。
這將在前一個運算符的線程上同步執行。

如果getFacility需要的時間寶貴的金額可能會與平行檢索flatMap

events.doOnNext(event -> Observable.fromIterable(event.facilityIds) 
      .flatMap(facilityId -> 
        Observable.fromCallable(() -> service.getFacility(facilityId)) 
        .subscribeOn(Schedulers.computation())) 
      .blockingSubsribe(facility -> event.facilities.add(facility))) 

但在這種情況下,導致facilities的順序不保證。

+0

使用* flatMap *而不是* map *會更好嗎?因爲我認爲'service.getFacility'可能需要一些時間來回應... –

+0

@ oliv37是的,你是對的。我將提供平行版本。你知道如何在平行執行的情況下保證啓動順序嗎?因爲我從來沒有嘗試過。 – Beloo

+0

我得到了一個稍微不同的解決方案,但是對於'forEach'的使用讓我走上了正確的道路,謝謝。 – oldergod

2

有一個元組或中介類與事件和ID。

events 
    .flatMap(evt -> Observable::fromIterable(Event::getFacilityIds(evt)).map(id -> new Tuple(evt, id))) 

它只是在範圍內,當你捕獲它。

public class Tuple<X, Y> { 
    public final X x; 
    public final Y y; 
    public Tuple(X x, Y y) { 
    this.x = x; 
    this.y = y; 
    } 
}