我有2个RxJava observable,返回相同类型的Pojo对象。一个来自我的本地数据库,另一个来自我的网络服务器。
这是我的2个可观察者
Observable<List<Wall>> favsLocal = ThemeApp.getInstance().getRepository().getFavsSingle();
Observable<List<Wall>> favsRemote = RestClient.getClient().getFavorite(WallInterface.FAV_GET, ThemeApp.getInstance().getPrefs().getUserEmail()).map(WallResponse::getWallList);
我想要实现的是两种方式同步收藏。所以我需要比较两者的结果,不需要将本地数据库中的任何内容发送到服务器,反之亦然。
favsRemote
.onErrorResumeNext(throwable -> {
throwable.printStackTrace();
return Observable.empty();
})
.subscribeOn(Schedulers.io())
.subscribeOn(Schedulers.io())
.zipWith(favsLocal,
(wallListLocal, wallListRemote) -> {
HashMap<String,List<Wall>> hashMap = new HashMap<>();
List<Wall> wallList = new ArrayList<>();
for(Wall wall : wallListLocal){
if (!wallListRemote.contains(wall)) {
wallList.add(wall);
}
}
hashMap.put("Local", wallList);
List<Wall> wallList2 = new ArrayList<>();
for(Wall wall : wallListRemote){
if (!wallListLocal.contains(wall)) {
wallList.add(wall);
}
}
hashMap.put("Remote", wallList2);
return hashMap;
})
.subscribeOn(Schedulers.io())
.subscribe(wallStringHashMap -> {
for (String key : wallStringHashMap.keySet()){
if (key.equalsIgnoreCase("Local")){
for (Wall wall : wallStringHashMap.get(key)) {
wall.setIsFav(true);
ThemeApp.getInstance().getRepository().setFavorite(wall);
}
} else {
for (Wall wall : wallStringHashMap.get(key)) {
RestClient.getClient().putFavorite(WallInterface.FAV_ADD, ThemeApp.getInstance().getPrefs().getUserEmail(), wall.getWallId())
.subscribeOn(Schedulers.io())
.subscribe(response -> {
List<ServerResponseItem> msg = response.getResponse();
},throwable -> {
throwable.printStackTrace();
Crashlytics.logException(throwable);
});
}
}
}
},throwable -> {
throwable.printStackTrace();
Crashlytics.logException(throwable);
},()->{
Log.d(TAG, "syncFavorites success");
});
这就是我目前正在做的事情,但似乎应该有更容易的事情。