您的位置:首页 > 编程语言 > Java开发

RxStore_一个使用RxJava的轻量级的数据持久化框架(一)

2016-01-27 16:43 597 查看
如果你的项目中已经使用了RxJava,那么Rxstore是一个简单的持久化框架,就很适合你。有很多场合你不需要一个复杂的数据库,你只需要一个简单的put/get接口,用来保存一些键值对,或者对象(包括列表对象)。

Rxstore中可以使用你喜欢的序列化格式,只要你提供一个有效的转换器。默认提供了 Gson 和 Jackson。Rxstore的另一个有点就是基于RxJava的“链接”形式。一旦你习惯这种编程方式,当你吃汤圆都想用竹签串起来吃。

在Java中:

RxStore myStore = RxStore.with(someDirectory).using(new GsonConverter());

在Android中:

RxStore myStore = RxStore.withContext(context)
.in("someDir")
.using(new GsonConverter());

这个Android方法将使用您应用程序的私有目录。
in()
允许你指定一个目录。

举个例子:

这是我们要保存的对象的结构。

public class Dino {
public String name;
public int armLength;
}

Dino dino = new Dino("Gregory", 37);


推荐时用单例模式:

RxStore rxStore = RxStore.withContext(context)
.in("dinoDir")
.using(new GsonConverter());

Dino dino = new Dino("Gregory", 37);

rxStore.put("dino", dino)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe((persistedDino) -> {
// Do something with your persisted dino.
});


rxStore.get("dino", Dino.Class)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe((Dino dino) -> {
// Do something with your persisted dino.
});
List<Dino> dinos = getDinoList(); //Some method that returns an ArrayList of Dinos.
rxStore.putList("dinoList", dinos, Dino.class)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThead())
.subscribe((persistedDinos) -> {
// Do something with your persisted dino army.
});



如果你使用Retrofit,那么久会很方便。你可以一次就把从网络上取到的数据保存到本地。


webServices.getDino()
.flatMap((dino) -> rxStore.put("dino", dino))
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe((dino) -> {
// Behold the downloaded and persisted dino
});




For the base library

compile 'au.com.gridstone.rxstore:rxstore:4.0.0'


For the Gson converter

compile 'au.com.gridstone.rxstore:converter-gson:4.0.0'


For the Jackson converter

compile 'au.com.gridstone.rxstore:converter-jackson:4.0.0'


github地址
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: