使用Realm和Retrofit以及RxJava存储数据

时间:2016-09-22 08:45:58

标签: android realm rx-java retrofit2

有人能为我提供一个使用Retrofit和RxJava将数据保存到Realm数据库的好例子吗?谢谢。

1 个答案:

答案 0 :(得分:2)

创建通过Retrofit Service下载数据并保留到Realm

的订阅
// I am trying to calculate the average, but cannot use filter, because I am in map block.

LabeledPoint(
  event.someColumn,
  Vectors.dense(
    averageAbove,
    ...
  )
)

将对象持久保存到Realm中的位置

    Subscription downloadCats = Observable.create(new RecyclerViewScrollBottomOnSubscribe(recyclerView))
            .filter(isScroll -> isScroll || realm.where(Cat.class).count() <= 0)
            .switchMap(isScroll -> catService.getCats().subscribeOn(Schedulers.io())) //
            .retry()
            .subscribe(catsBO -> {
                catPersister.persist(catsBO);
            }, throwable -> {
                Log.e(TAG, "An error occurred", throwable);
            });
    compositeSubscription.add(downloadCats);

显示数据并使用

在UI线程上保持最新
  • try(Realm r = Realm.getDefaultInstance()) { // on background thread r.executeTransaction((realm) -> { Cat defaultCat = new Cat(); long rank; if(realm.where(Cat.class).count() > 0) { rank = realm.where(Cat.class).max(CatFields.RANK).longValue(); } else { rank = 0; } for(CatBO catBO : catsBO.getCats()) { defaultCat.setId(catBO.getId()); defaultCat.setRank(++rank); defaultCat.setSourceUrl(catBO.getSourceUrl()); defaultCat.setUrl(catBO.getUrl()); realm.insertOrUpdate(defaultCat); } }); }
  • 或其他订阅RealmRecyclerViewAdapter
realm.where(Cat.class).findAllSortedAsync(...).asObservable().filter(RealmResults::isLoaded).subscribe()
    recyclerView.setAdapter(new CatAdapter(getContext(),
            realm.where(Cat.class).findAllSortedAsync(CatFields.RANK, Sort.ASCENDING)));