2016-01-29 99 views
0

我有一個測試案例採取和防抖動使用率問題

public void testLimitAndPublishSubject() throws InterruptedException { 
    PublishSubject<Boolean> mBooleanPublishSubject = PublishSubject.create(); 
    mBooleanPublishSubject.asObservable() 
      .doOnEach(__ -> System.out.println("on value emitted "+System.currentTimeMillis())) 
      .take(1) 
      .doOnEach(__ -> System.out.println("on value emitted 2 "+System.currentTimeMillis())) 
      .debounce(1000, TimeUnit.MILLISECONDS) 
      .doOnEach(__ -> System.out.println("on value emitted 3 "+System.currentTimeMillis())) 
      .subscribe(__ -> System.out.println("done "+System.currentTimeMillis())); 
    mBooleanPublishSubject.onNext(true); 
    Thread.sleep(1000); 
    mBooleanPublishSubject.onNext(true); 
    Thread.sleep(2000); 
} 

和輸出

on value emitted 1454063289770 
on value emitted 2 1454063289770 
on value emitted 2 1454063289779 
on value emitted 3 1454063289780 
done 1454063289780 
on value emitted 3 1454063289780 

我想不通爲什麼on value emitted 2on value emitted 3出現在日誌中兩次,爲什麼去抖延遲不起作用。有人可以幫忙嗎?

回答

0

討論here

要解決的問題記錄重複的項目,我應該使用doOnNext代替doOnEach,如doOnEach包括onCompleted事件

take(1)立即完成觀察到的,這就是爲什麼防抖不起作用。應該使用延遲代替

mBooleanPublishSubject.asObservable() 
     .doOnNext(__ -> System.out.println("on value emitted " + System.currentTimeMillis())) 
     .take(1) 
     .doOnNext(__ -> System.out.println("on value emitted 2 " + System.currentTimeMillis())) 
     .delay(1, TimeUnit.SECONDS) 
     .doOnNext(__ -> System.out.println("on value emitted 3 " + System.currentTimeMillis())) 
     .subscribe(__ -> System.out.println("done " + System.currentTimeMillis()));