2016-12-06 39 views
1

如何在RxJava中暴露多個回調的單個操作(例如START帶有一些參數,PROGRESS多次使用其他參數調用,END使用其他參數)?在RxJava中使用多個回調的單個操作

我想使用包含一個可觀察的各種回調以及任何可觀察到的那些的簽約觸發與其他綁定在相同的底層操作的操作開始時的包裝對象

編輯:一個例子回調接口爲下載操作

interface Callback { 
    void onDownloadStarted(long contentLength, String mimeType, String nameHint); 
    void onDownloadProgress(long downloadedBytes); 
    void onDownloadCompleted(File file); 
} 
+0

你想要什麼要執行的操作? –

+0

@TassosBassoukos添加了一個示例回調接口 –

回答

1

你可以把你的操作爲Observable<Status>其中

public static class Info { 
    public final long contentLength; 
    public final String mimeType; 
    public final String nameHint; 
    public Info(long contentLength, String mimeType, String nameHint) { 
     this.contentLength = contentLength; 
     this.mimeType = mimeType; 
     this.nameHint = nameHint; 
    } 
} 
public static class Status { 
    public final Info info; 
    public final long downloadProgress; //in bytes 
    public final Optional<File> file; 
    public Status(Info info, long downloadProgress, Optional<File> file) { 
     this.info = info; 
     this.downloadProgress = downloadProgress; 
     this.file = file; 
    } 
} 

然後,你可以在你的下載運營模式爲:

Observable<Status> download();

你沒有排放,直到下載已經開始和最後的發射有File結果。

你可以使用這樣的:

download() 
    .doOnNext(status -> System.out.println(
     "downloaded " 
     + status.downloadProgress 
     + " bytes of " + status.contentLength)) 
    .last() 
    .doOnNext(status -> System.out.println(
     "downloaded " + status.file.get()) 
    .doOnError(e -> logError(e)) 
    .subscribe(); 
+0

令人害怕的東西是對象分配/ gc暫停(我在android上)的事件,比如基於會產生很多字節的進度。在這種情況下,每個緩衝區讀/寫(例如8K)它將分配一個新的狀態對象? –

+0

沒錯,但是你不必每8K發射一次。你有所有的計數信息,你需要確保你只發出每1%或5%,這是一個微不足道的數量。 –

相關問題