How to use switchIfEmpty?

我只是一个虾纸丫 提交于 2019-12-11 06:26:11

问题


I need to fetch data from DB. If it's empty, get data from server and insert it into database. Here is my code,

public Flowable<List<Data>> test() {
    return dataDao.allDatas()
           .switchIfEmpty(datas())
                .doOnNext(datas -> userStoreDao.insert(datas))
           );
}

public Flowable<List<Data>> datas() {
    return Flowable.zip(userFavoriteDatas(), userOtherDatas(),
        (favoriteDatas, otherDatas) -> {
            favoriteDatas.addAll(otherDatas);
            return favoriteDatas;
        });
}

public Flowable<List<Data>> userFavoriteDatas() {
    return userDatas()
        .map(UserDatas::favoriteDatas)
        .flatMapIterable(datas-> datas)
        .map(aLong -> new UserData(aLong, 1))
        .toList()
        .toFlowable();
}

public Flowable<List<Data>> userOtherDatas() {
    return userDatas()
        .map(UserDatas::otherDatas)
        .flatMapIterable(datas-> datas)
        .map(aLong -> new UserData(aLong, 1))
        .toList()
        .toFlowable();
}

private Flowable<Datas> userDatas() {
    return api
        .userDatas()
        .toFlowable()
        .share(); 
}

@GET("user/datas")
Single<Datas> datas();

It reaches second part when the first part returns empty result. datas() doesn't reached till the end while I'm running only the second part it works but combining with switchIfEmpty() it reaches to userDatas() and doesn't complete

I tried concat() as well with the same result.


回答1:


(From the comments):

If you use toList, that requires a finite stream. Based on the OP's feedback, the allDatas source was infinite but returned an empty List. The resolution was to apply at least take(1) to get exactly one response from allDatas and then optionally filter out the empty List so switchIfEmpty can switch over to the alternatives:

return allDatas.take(1).filter(list -> !list.isEmpty())
       .switchIfEmpty(datas())
       .doOnNext(datas -> userStoreDao.insert(datas));


来源:https://stackoverflow.com/questions/45549827/how-to-use-switchifempty

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!