2017-04-05 86 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产生新的计时器可观察到的每一次,该定时器值被更新。

但是,在此决定中,您需要注意取消订阅。