2016-09-21 57 views
0

我正在學習rxjava,並被一個窗口操作符卡住。我在我的Android設備上測試以下簡單代碼,並得到令人困惑的結果。Rxjava窗口()令人困惑的結果

代碼:

Observable.interval(100, TimeUnit.MILLISECONDS) 
    .take(10) 
    .window(250, 100, TimeUnit.MILLISECONDS) 
    .flatMap(o -> o.toList()) 
    .subscribe(o -> Log.d(TAG, "object: "+o)); 

有時候,我得到的是看起來像我正確的結果:

object: [0, 1] 
object: [0, 1, 2] 
object: [1, 2, 3] 
object: [2, 3, 4] 
object: [3, 4, 5] 
object: [4, 5, 6] 
object: [5, 6, 7] 
object: [6, 7, 8] 
object: [7, 8, 9] 
object: [8, 9] 
object: [9] 

但有時候,我得到這樣的

object: [0, 1] 
object: [0, 1, 2] 
object: [1, 2, 3] 
object: [2, 3, 4] 
object: [3, 4, 5] 
object: [4, 5, 6] 
object: [6, 7] 
object: [6, 7, 8] 
object: [7, 8, 9] 
object: [8, 9] 
object: [9] 

誰能解釋爲什麼這個代碼的結果不同?

回答

0

代碼不立即執行。正如你從日誌中看到的那樣,在next事件上發射的差異很小,所以它不等於100毫秒的多重性。如果你添加窗口運算符差距更大。在這段代碼有如果onNext事件擊中錯誤的窗口

Observable.interval(100, TimeUnit.MILLISECONDS) 
     .doOnNext(new Action1<Long>() { 
      @Override 
      public void call(Long aLong) { 
       Log.d(TAG, "ON NEXT TIME " + System.currentTimeMillis() % 10000); 
      } 
     }) 
     .take(10) 
     .window(250, 100, TimeUnit.MILLISECONDS) 
     .subscribe(new Action1<Object>() { 
      @Override 
      public void call(Object aLong) { 
       Log.d(TAG, "SUBSCRIBE TIME: " + System.currentTimeMillis() % 10000); 
      } 
     }); 

日誌無窗操作

SOME_TAG: ON NEXT TIME 8445 
SOME_TAG: SUBSCRIBE TIME: 8445 
SOME_TAG: ON NEXT TIME 8545 
SOME_TAG: SUBSCRIBE TIME: 8545 
SOME_TAG: ON NEXT TIME 8646 
SOME_TAG: SUBSCRIBE TIME: 8646 
SOME_TAG: ON NEXT TIME 8745 
SOME_TAG: SUBSCRIBE TIME: 8745 
SOME_TAG: ON NEXT TIME 8846 
SOME_TAG: SUBSCRIBE TIME: 8846 
SOME_TAG: ON NEXT TIME 8945 
SOME_TAG: SUBSCRIBE TIME: 8945 
SOME_TAG: ON NEXT TIME 9045 
SOME_TAG: SUBSCRIBE TIME: 9045 
SOME_TAG: ON NEXT TIME 9145 
SOME_TAG: SUBSCRIBE TIME: 9146 
SOME_TAG: ON NEXT TIME 9245 
SOME_TAG: SUBSCRIBE TIME: 9245 
SOME_TAG: ON NEXT TIME 9345 
SOME_TAG: SUBSCRIBE TIME: 9345 

日誌與窗口操作可能會導致不必要的行爲邊界情況

SOME_TAG: ON NEXT TIME 7622 
SOME_TAG: SUBSCRIBE TIME: 7718 
SOME_TAG: ON NEXT TIME 7722 
SOME_TAG: SUBSCRIBE TIME: 7818 
SOME_TAG: ON NEXT TIME 7822 
SOME_TAG: SUBSCRIBE TIME: 7918 
SOME_TAG: ON NEXT TIME 7922 // THIS 
SOME_TAG: SUBSCRIBE TIME: 8018 
SOME_TAG: ON NEXT TIME 8023 // COMPARE WITH THIS 
SOME_TAG: SUBSCRIBE TIME: 8118 
SOME_TAG: ON NEXT TIME 8122 
SOME_TAG: SUBSCRIBE TIME: 8218 
SOME_TAG: ON NEXT TIME 8223 
SOME_TAG: SUBSCRIBE TIME: 8319 
SOME_TAG: ON NEXT TIME 8323 
SOME_TAG: SUBSCRIBE TIME: 8419 
SOME_TAG: ON NEXT TIME 8422 
SOME_TAG: SUBSCRIBE TIME: 8518 
SOME_TAG: ON NEXT TIME 8522