2017-05-19 52 views
0

我有下載器通過套接字發送下載的百分比到前端。它看起來像這樣:JavaRx:我可以設置觀察值的默認值,無需用戶的反應?

DownloadStream downloadStream = SomeService.downloadStream(someFile); 
Long total = downloadStream.totalSize(); 
Subject totalDownloaded = new BehaviorSubject.createDefault(0); 
Disposable downloadSubscriber = totalDownloaded.subscribe(downloaded -> { 
    Message message = new Message(downloaded, total); 
    send(message); 
}); 


Long downloaded = downloadStream.stream(); //stream() is bulk read/write. 
while(downloaded != -1L) { 
    chunk = downloadStream.stream(); 
    totalDownloaded.onNext(totalDownloaded.value + chunk); 
} 

但問題是,defaultValue = 0調用訂閱的lambda。我如何定義沒有副作用的默認值?或者有一些增加可觀察的解決方案長?請幫助...

回答

0

您可以使用flatMap()filter()函數刪除值。

實施例:

// create sequence 
    Observable<Integer> o = Observable.just(0, 10, 25, 32, 56, 74, 100); 

    System.out.println("all values:"); 
    o.subscribe(a -> System.out.printf("%d%%; ", a)); 

    System.out.println("\n\nfilter by flatMap:"); 
    o.flatMap(val -> { 
       if(val > 5) 
        return Observable.just(val); 
       else 
        return Observable.empty(); 
      }) 
      .subscribe(a -> System.out.printf("%d%%; ", a)); 

    System.out.println("\n\nfilter by filter():"); 
    o.filter(val -> val > 15) 
      .subscribe(a -> System.out.printf("%d%%; ", a));