Reputation: 281
How a single operation with multiple callbacks (e.g. START with some params, PROGRESS called multiple times with other params and END with other params) should be exposed in RxJava?
I'm thinking to use a wrapper object that contains an observable for each kind of callback and that a subscription on any of those observable triggers the start of the operation with the other binded on the same underlying operation
EDIT: An example callback interface for a download operation
interface Callback {
void onDownloadStarted(long contentLength, String mimeType, String nameHint);
void onDownloadProgress(long downloadedBytes);
void onDownloadCompleted(File file);
}
Upvotes: 1
Views: 523
Reputation: 12097
You could think of your operation as an Observable<Status>
where
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;
}
}
Then you could model your download operation as:
Observable<Status> download();
You get no emissions till the download has started and the final emission has the File
result.
You could use it like this:
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();
Upvotes: 1