我是rxJava和Retrofit2的新手,但我似乎无法弄清楚如何实现所需的情况:
- 获取地点列表(Retrofit2 API接口)这将给出一个JSON数组与地点对象
- 把JSON数组在HashMap(在哪里处理这个?)
- 把HashMap放在Singleton中,这样它就可以被缓存,并且可以在整个应用中使用getInstance来调用
JSON数组包含数百个我希望缓存的"地方"(Singleton),所以我不必为应用程序中的每个更改调用。
界面(myAPI)
/**
* RxJava testing endpoint
* @return Observable list of Places
* count = 0 means everything
*/
@GET("place/search?count=0")
rx.Observable<List<Place>> loadPlacesRx();
单例
...
private static PlaceSingleton ourInstance = new PlaceSingleton();
private static RxJavaCallAdapterFactory rxAdapter =
RxJavaCallAdapterFactory.createWithScheduler(Schedulers.io());
private static Retrofit retrofit = new Retrofit.Builder()
.addConverterFactory(JacksonConverterFactory.create())
.addCallAdapterFactory(rxAdapter)
.baseUrl(myAPI.BASE_URL)
.build();
// Prepare call in Retrofit2
private static MyAPI myAPI = retrofit.create(MyAPI.class);
/**
* This method should handle the steps mentioned above
*/
public void getAllPlaces() {
poiList = myAPI.loadPlacesRx()
.map(Place -> ...
...
您可以将自己的缓存序列化对象保存为字符串,使用Gson并将其保存为共享首选项。
使用Gson:serializate:
new Gson().toJson(yourObject);
和反序列化:
new Gson().fromJson(stringObject);
使用Jakson: serializate :
ObjectMapper mapper = new ObjectMapper();
String objectString = mapper.writeValueAsString(object);
deserializate :
ObjectMapper mapper = new ObjectMapper();
Object object = mapper.readValue(jsonInString, Object.class);