2017-06-08 39 views
3

假设我有一些复杂的链Single,MaybeObservable执行一些任务的对象。如何可视化RxJava图的执行?

例如:

// Download, unzip and parse a release 
public static Single<Release> fetchRelease(final Release release) { 
    final Path cachePath = getCachePath(release); 
    return download(release.url, cachePath, true).ignoreElements() 
     .andThen(hash(cachePath)) 
     .flatMap(fileHash -> unzip(cachePath) 
      .andThen(parseFile(unzipTargetPath))); 
} 

这些连锁店可能在多个线程中运行。

问题是,我想将这些任务的进度呈现给用户,而不会在可能的情况下混淆他们的逻辑。

例如,上面的任务可能会显示:

+-Fetching release 1.0... Done 
    +-Downloading https://www.example.com/v1.0.0.zip 100% 
    +-Hashing Library/Caches/Example/v1.0.0.zip... Done 
    +-Unpacking Library/Caches/Example/v1.0.0.zip 
    +-src.. Done 
    +-tests... Done 
    +-resources... Done 
    +-Parsing release... Done 

理想情况下,我也想显示任务的层次结构。这目前只在Java调用图中编码。

我现在的想法是:

  • 改变每Single一个Observable,其中最后一个元素是结果,其他的是最新进展。
  • 为任务的每个阶段编写事件类。

我认为这会使代码不易读,导致大量锅炉板。

public final class DownloadProgress { 
    public final float progress; 
    // etc.. 
} 

// etc... 

public final class FetchReleaseProgress { 
    public final Variant<DownloadProgress, HashingProgress, UnpackProgress, ParseProgress> progress; 
    // etc... 
} 

推荐的方法是什么?

+0

你可以看看htrace – raam86

+0

使用RxJavaPlugin –

回答

0

你以正确的方式,你可以写,表示你感兴趣的UI事件完整的UI模型,我会在这里把你的情况为例

+-Fetching release 1.0... Done 
    +-Downloading https://www.example.com/v1.0.0.zip 100% 
    +-Hashing Library/Caches/Example/v1.0.0.zip... Done 
    +-Unpacking Library/Caches/Example/v1.0.0.zip 
    +-src.. Done 
    +-tests... Done 
    +-resources... Done 
    +-Parsing release... Done 

和模型可以是财产以后这样的:

final class DownloadUiModel { 
private float progress; 
private String hashing; 
private String downloading; 
private String unpacking; 
private String done; 

private DownloadUiModel(float progress, String hashing //..etc) { 
} 
//getters 
//setters 
} 

然后用Rxjava可能你会用以前的型号如下:

download(release.url, cachePath, true) 
.ignoreElements() 
.map(response -> downloadUiModel.setDownloading(release.url)) 
.andThen(hash(cachePath)) 
.map(response -> downloadUiModel.setHashing(cachePath)) 
.flatMap(fileHash -> unzip(cachePath) 
.andThen(parseFile(unzipTargetPath))) 
.map(response -> downloadUiModel.setUnzipping(unzipTargetPath)) 
... 

然后订阅时,您可以使用此UI模型来更新你的UI,像这样

downloadObservable.subscribe(model -> 
if(model.getProgress()!= 100){ 
Timber.d(model.getDownloading()) 
Timber.d(model.getHashing()) 
Timber.d(model.getUnpacking)) 
//... 
} 

这个方式,你的UI逻辑是从您的请求逻辑分隔漂亮的一部分,你可以伊斯利切换到Android主线程安全。