可使用RxJava从Cache流动,以及DataSource的其他Flowable

时间:2019-05-27 13:51:11

标签: java rx-java rx-java2 repository-pattern

对于RxJava来说我还很陌生,我需要使用几个数据源创建存储库。这对我来说很复杂,因为有几个较小的子任务,我不知道如何用RxJava来实现。

我有Dao,它为DataSource类提供了Flowable<Item>。该数据源具有本地缓存​​,该缓存可以随时失效。当存储库向DataSource询问某个范围(可能超出DataSourse范围,在完全缓存之前,范围是未知的)时,它必须产生一个错误(或以其他方式通知存储库)。

我想为DataSource创建Flowable<Item>方法,该方法将从缓存中发射项目,并且如果需要,将它们与Flowable<Item> dao.getRange(...)连接起来,同时缓存来自dao的新项目。另外,我还需要处理来自dao的错误,必须将其处理或转换为更高级别的错误。

DataSource.class

List<Item> cache;

Flowable<Item> getRange(int start, int amount) {

    final int cacheSize = cache.size();
    final int canLoadFromCache = cacheSize - start;
    final int loadFromDao = amount - canLoadFromCache;

    if (isCorrupted) return Flowable.fromCallable(() -> {
        throw new Exception("CorruptedDatasource");
    });

    Flowable<Item> cacheFlow = null;
    Flowable<Item> daoFlow = null;

    if (canLoadFromCache > 0) {
        cacheFlow = Flowable.fromIterable(
                cache.subList(start, canLoadFromCache)
        );

        daoFlow = dao.getRange(
                uri, 
                cacheSize, //start
                loadFromDao //amount
        );
    } else {
        if (isFullyCached) return Flowable.fromCallable(() -> {
            throw new Exception("OutOfBounds");
        });

        //To not deal with gaps load and cache data between;
        //Or replace it with data structure which can handle for us;
        daoFlow = dao.getRange(
                uri,
                cacheSize,
                start - cacheSize + amount);
        //all these items should be cached;
        //other cached and put downstream;
        //Dao errs should be converted to higher lever exceptions,
        //Or set flags in DataSource;
    }
    // return concatenated flowable;
}

在较高级别的存储库中,将来自多个数据源的数据连接起来,因此,必须有一种方法可以以多种方式来分类来自多个数据源的范围,如果一个数据源不足,则应添加下一个数据域的范围。

请帮助我!

1 个答案:

答案 0 :(得分:0)

尝试使用concatconcatEager连接两个可观察对象。此外,doOnNext()doOnError()可以帮助您进行缓存和错误处理

List<Item> cache;

Flowable<Item> getRange(int start, int amount) {

    ...
        if (isFullyCached) return Flowable.fromCallable(() -> {
            throw new Exception("OutOfBounds");
        });

        //To not deal with gaps load and cache data between;
        //Or replace it with data structure which can handle for us;
        daoFlow = dao.getRange(
                uri,
                cacheSize,
                start - cacheSize + amount);
        //all these items should be cached;
        //other cached and put downstream;
            .doOnNext(result -> /* insert caching logic here */)
        //Dao errs should be converted to higher lever exceptions,
        //Or set flags in DataSource;
            .doOnError(error -> /* handle error here */)
            .onErrorReturn(/* and/or return some empty item */)
    }
    // return concatenated flowable;
    return cacheFlow.concat(daoFlow);
}