2015-06-09 98 views
0

我有一個多個按鈕;當我按下新按鈕時,之前(與另一個按鈕)運行請求應該被中斷並且新的運行。如何實現它?如何取消網絡請求改造和rxjava

for (button : Buttons) { 
button.setOnClickListener(b -> networkApi.getLongContentFromUrl(url) 
        .observeOn(AndroidSchedulers.mainThread()) 
        .subscribe(new Subscriber<JsonElement>() { 
         @Override 
         public void onCompleted() {} 

         @Override 
         public void onError(Throwable e) { 
         } 

         @Override 
         public void onNext(JsonElement jsonElement) { 
          //do with result 
         } 
        })); 
    } 

回答

3

您可以有一個共同的SerialSubscription並通過按鈕單擊將您的訂戶分配給它。它將取消訂閱,從而取消您之前的數據流:

SerialSubscription serial = new SerialSubscription(); 
for (Button btn : buttons) { 
    btn.setOnClickListener(e -> { 
     Subscriber<JsonElement> s = new Subscriber<JsonElement>() { 
      @Override 
      public void onCompleted() {} 
      @Override 
      public void onError(Throwable e) {} 
      @Override 
      public void onNext(JsonElement jsonElement) { 
       //do with result 
      } 
     }; 
     serial.set(s); 
     networkApi.getLongContentFromUrl(url) 
       .observeOn(AndroidSchedulers.mainThread()) 
       .subscribe(s); 
    }); 
}