Sample 1: RxJava的Hello World
private Subscriber<String> mSubscriber = new Subscriber<String>() {
@Override
public void onCompleted() {
Log.d(TAG, "onCompleted");
}
@Override
public void onError(Throwable e) {
Log.d(TAG, "onError");
}
@Override
public void onNext(String s) {
Log.d(TAG, "onNext # " + s);
}
};
...
Observable<String> observable = Observable.create(new Observable.OnSubscribe<String>() {
@Override
public void call(Subscriber<? super String> subscriber) {
subscriber.onNext("hello world");
subscriber.onCompleted();
}
});
observable.subscribe(mSubscriber);
Sample 2: 更简洁的实现
Observable.just("hello world 2").subscribe(new Action1<String>() {
@Override
public void call(String s) {
Log.d(TAG, "simpler # " + s);
}
});
Sample 3: map转换操作
Observable.just("hello world 3")
.map(new Func1<String, String>() {
@Override
public String call(String s) {
return s + " from syl";
}
})
.subscribe(new Action1<String>() {
@Override
public void call(String s) {
Log.d(TAG, "transform # " + s);
}
});
**Sample 4: **
Network.getGitHubApi().rxListRepo("octocat")
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.flatMap(new Func1<List<Repo>, Observable<Repo>>() {
@Override
public Observable<Repo> call(List<Repo> repos) {
return Observable.from(repos);
}
})
.filter(new Func1<Repo, Boolean>() {
@Override
public Boolean call(Repo repo) {
return repo != null;
}
})
.take(3)
.subscribe(new Action1<Repo>() {
@Override
public void call(Repo repo) {
Log.d(TAG, "" + repo.getFull_name());
}
});
RxSamples:RxJava 和 Retrofit 结合使用的几个最常见使用方式举例。
- 1 基本:
subscribeOn()
+observeOn()
private void search(String key) {
subscription = Network.getZhuangbiApi()
.search(key)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(observer);
}
2 转换:
map()
3 压合:
zip()
4 Token:
flatMap()
获取token -> 请求网络数据with token
@OnClick(R.id.requestBt)
void upload() {
swipeRefreshLayout.setRefreshing(true);
unsubscribe();
final FakeApi fakeApi = Network.getFakeApi();
subscription = fakeApi.getFakeToken("fake_auth_code")
.flatMap(new Func1<FakeToken, Observable<FakeThing>>() {
@Override
public Observable<FakeThing> call(FakeToken fakeToken) {
return fakeApi.getFakeData(fakeToken);
}
})
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Action1<FakeThing>() {
@Override
public void call(FakeThing fakeData) {
swipeRefreshLayout.setRefreshing(false);
tokenTv.setText(getString(R.string.got_data, fakeData.id, fakeData.name));
}
}, new Action1<Throwable>() {
@Override
public void call(Throwable throwable) {
swipeRefreshLayout.setRefreshing(false);
Toast.makeText(getActivity(), R.string.loading_failed, Toast.LENGTH_SHORT).show();
}
});
}
- 5 Token高级:
flatMap()
+retryWhen()
- 6 缓存:
BehaviorSubject<T>
内存缓存 -> 磁盘缓存 -> 请求网络数据