2017-06-17 74 views
0

我試圖在調用活動onDestroy時執行一些操作。我想用一個ID啓動一個Observable,然後從Realm中檢索一些數據,並根據檢索到的數據向後端執行一個HTTP請求,然後將檢索到的數據存儲到由起始ID給出的行中。如何鏈接多個observable與RxJava?

總結:

  1. ID爲檢索來自數據庫的數據
  2. 使用數據,以執行到後端
  3. 存儲檢索到的數據從步驟與ID到行的請求1

圖示:

expected flow

代碼: 什麼我結束了和卡住了

Observable.just(id) 
     .observeOn(Schedulers.io()) 
     .map(new Function<String, Person>() { 
      @Override 
      public Person apply(@NonNull String id) throws Exception { 
       Realm realm = Realm.getDefaultInstance(); 

       Person person = realm.copyFromRealm(realm.where(Person.class).equalTo("id", id).findFirst()); 

       realm.close(); 

       return person; 
      } 
     }) 
     .switchMap(new Function<Person, Observable<Directions>>() { 
      @Override 
      public Observable<Directions> apply(@NonNull Person person) throws Exception { 
       return Utils.getRemoteService().getDirections(person.getAddress()); // retrofit 
      } 
     }) 
     .map(new Function<Directions, Object>() { 
      @Override 
      public Object apply(@NonNull Directions directions) throws Exception { 

       // how do I get the id here to store the data to the correct person 

       return null; 
      } 
     }) 
     .subscribe(); 

注:

  • POJO的是虛構
  • 它使用是我第一次RxJava

回答

0

信息必須傳遞到流中,它可以像下面那樣完成。當你將它包裝在一個類中而不是Pair中時,它會更具可讀性。

Observable.just(id) 
      .observeOn(Schedulers.io()) 
      .map(new Function<String, Person>() { 
       @Override 
       public Person apply(@NonNull String id) throws Exception { 
        Realm realm = Realm.getDefaultInstance(); 

        Person person = realm.copyFromRealm(realm.where(Person.class).equalTo("id", id).findFirst()); 

        realm.close(); 

        return person; 
       } 
      }) 
      .switchMap(new Function<Person, Observable<Directions>>() { 
       @Override 
       public Observable<Directions> apply(@NonNull Pair<String, Person> pair) throws Exception { 
        // assuming that id is available by getId 
        return Pair(person.getId(), Utils.getRemoteService().getDirections(person.getAddress())); // retrofit 
       } 
      }) 
      .map(new Function<Pair<String, Directions>, Object>() { 
       @Override 
       public Object apply(@NonNull Pair<String, Directions> pair) throws Exception { 

        // how do I get the id here to store the data to the correct person 
        // pair.first contains the id 
        // pair.second contains the Directions 
        return null; 
       } 
      }) 
      .subscribe();