RxJava2学习之九:购物车合并本地和网络数据

RxJava操作符

本例涉及的RxJava操作符:

  • Merge将两个Observable发射的数据组合并成一个

结合使用 Retrofit转换器 GsonConverterFactory 和其 RxJava适配器 RxJavaCallAdapterFactory

RxJava实现

添加依赖

1
2
3
compile 'com.squareup.retrofit2:retrofit:2.1.0'
compile 'com.squareup.retrofit2:converter-gson:2.1.0'
compile 'com.squareup.retrofit2:adapter-rxjava:2.1.0'

业务请求接口

1
2
3
4
5
6
public interface Api {

@GET("courses")
Observable<List<Course>> getCourses();

}

RxJava实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
public void merge(View view) {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(SERVER_ADDRESS)
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
.build();

api = retrofit.create(Api.class);

//Merge合并操作符
Observable.merge(getDatasFromLocal(), getDatasFromNetWork())
.subscribe(new Subscriber<List<Course>>() {
@Override
public void onCompleted() {
Log.i(TAG, "onCompleted: ");
}

@Override
public void onError(Throwable e) {
e.printStackTrace();
}

@Override
public void onNext(List<Course> courses) {
for (Course cource : courses){
Log.i(TAG, "onNext: " + cource.getName());
}
}
});
}

private Observable<List<Course>> getDatasFromLocal(){
List<Course> list = new ArrayList<>();
list.add(new Course("数学"));
list.add(new Course("语文"));
return Observable.just(list);
}

private Observable<List<Course>> getDatasFromNetWork(){
return api.getCourses().subscribeOn(Schedulers.io());
}

Python Flask服务端设计

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
@app.route("/courses")
def courses():
course1 = Cource(id="1", name="物理")
course2 = Cource(id="2", name="化学")

courses = {course1, course2}
json = jsonpickle.encode(courses, unpicklable=False)

return json


class Cource():
def __init__(self, id, name):
self.id = id
self.name = name

Powered by AppBlog.CN     浙ICP备14037229号

Copyright © 2012 - 2020 APP开发技术博客 All Rights Reserved.

访客数 : | 访问量 :