2017-06-17 71 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();