2016-07-27 38 views
1

如何可以結合兩個訂閱等:如何兩個訂閱連接在RXJava/Android的

1)改造& RX其將JSON成recyclerView所示的字符串列表。

restClient.getCatFacts() 
      .subscribeOn(Schedulers.newThread()) 
      .observeOn(AndroidSchedulers.mainThread()) 
      .subscribe(new Subscriber<CatFactsResponse>() { 
       @Override 
       public void onCompleted() { 
        Log.i(TAG, "onCompleted"); 
       } 

       @Override 
       public void onError(Throwable e) { 
        Log.i(TAG, "onError, " + e.getMessage()); 
       } 

       @Override 
       public void onNext(CatFactsResponse catFactsResponse) { 
        catFactsList = catFactsResponse.getCatFacts(); 
       } 
      }); 

2)和Jack Wharton的RxBinding庫對EditText小部件中所做的更改作出反應。

subscription = RxTextView 
      .textChangeEvents(editText) 
      .debounce(400, TimeUnit.MILLISECONDS) 
      .observeOn(Schedulers.newThread()) 
      .subscribe(new Observer<TextViewTextChangeEvent>() { 
       @Override 
       public void onCompleted() { 
        Log.i(TAG, "onCompleted"); 
       } 

       @Override 
       public void onError(Throwable e) { 
        Log.i(TAG, "onError >> " + e.getMessage()); 
       } 

       @Override 
       public void onNext(TextViewTextChangeEvent textViewTextChangeEvent) { 
        Log.i(TAG, textViewTextChangeEvent.text().toString()); 
       } 
      }); 

獲取使用EditText動態過濾的列表。我是否應該使用Subject或者某些類?如果是,那麼它應該是什麼樣子?感謝您的幫助:)

回答

1

您應該使用flatMap操作

subscription = RxTextView 
      .textChangeEvents(editText) 
      .debounce(400, TimeUnit.MILLISECONDS) 
      .map(new Func1<TextViewTextChangeEvent, String>() { 
       @Override 
       public String call(TextViewTextChangeEvent textViewTextChangeEvent) { 
        return textViewTextChangeEvent.text(); 
       } 
      }) 
      .flatMap(new Func1<String, Observable<CatFactsResponse>>() { 
       @Override 
       public Observable<CatFactsResponse> call(String text) { 
        return restClient.getCatFacts(text) 
          .subscribeOn(Schedulers.io()) 
          .observeOn(AndroidSchedulers.mainThread()); 
       } 
      }) 
      .subscribe(...); 
+0

出色答卷。現在我終於知道我該怎麼做這種關係了:) – Glaeqen