2017-06-17 4 views
0

アクティビティonDestroyが呼び出されたときに、いくつかのオペレーションを実行しようとしています。 ObservableをIDで開始し、Realmからいくつかのデータを取得し、取得したデータに基づいてバックエンドにHTTP要求を実行し、その後に取得したデータを開始IDで指定された行に格納します。RxJavaで複数のオブザーバブルをチェーンする方法は?

概要:

  1. ストアステップからIDと行にデータを取得
  2. バックエンドへの要求を実行するためのIDで
  3. 使用データをデータベースからデータを取得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(); 
関連する問題