2017-04-05 82 views
0

我正在爲Android應用程序倒計時。 到目前爲止倒計數從10到1,它工作正常。與RXJava倒計時並增加按鈕

Observable observable = Observable.interval(1, TimeUnit.SECONDS) 
      .take(10) // up to 10 items 
      .map(new Function<Long, Long>() { 
       @Override 
       public Long apply(Long v) throws Exception { 
        return 10 - v; 
       } 
      }); // shift it to 10 .. 1 

我有多個subscriptons類似如下:

//subscription 1 
    observable.subscribe(new Consumer<Long>() { 
       @Override 
       public void accept(Long countdown) throws Exception { 
        Log.e(TAG,"countdown: "+countdown); 
       } 
      }); 

    //subscription 2 
    observable.subscribe(new Observer() { 
     @Override 
     public void onSubscribe(Disposable d) { 

     } 

     @Override 
     public void onNext(Object value) { 
      //whatever 
     } 

     @Override 
     public void onError(Throwable e) { 

     } 

     @Override 
     public void onComplete() { 
      Log.d(TAG,"completed"); 
     } 
    }); 

首先:這是一個很好的用例?我做對了嗎?

我現在的問題是,我希望能夠增加任何時候用戶按下一個按鈕倒計時。 因此,我不能使用我目前的Observable,但我不知道如何實現它。 任何人都可以幫忙嗎? :)

+0

我看不出爲什麼你需要2個用戶。將您的使用者代碼放入subscription2的onNext()中。 –

+0

我想間隔是一個熱門的可觀察。如果您希望2訂閱者獲得相同的值,則需要重播()。autoConnect()。 –

+0

@PhoenixWang我不僅使用2,而且4用戶,因爲他們在不同的地方。可觀測數據處於服務中,1個用戶是UI中的倒計時,1個用戶在倒計時完成後立即更新按鈕,1個用戶啓動另一個服務。等等。我以爲那是我使用這種模式? – simmerl

回答

0

這是我的解決方案:

private BehaviorSubject<Long> timer = BehaviorSubject.create(); 

... 
    timer 
     .compose(bindToLifecycle()) // unsubscribe when view closed 
     .switchMap(time -> Observable.intervalRange(0, time, 0, 1, TimeUnit.SECONDS) 
       .map(t -> time - t)) // restart timer always when timeLeft have new value 
     .compose(bindToLifecycle()) // unsubscribe when view closed 
     .doOnNext(this::updateTimerView) 
     .subscribe(); 

... 
    onButtonClick(){ 
     timer.onNext(10); 
    } 

我用swithMap產生新的計時器可觀察到的每一次,該定時器值被更新。

但是,在此決定中,您需要注意取消訂閱。