1.添加依赖
//retrofit
compile 'com.squareup.retrofit2:retrofit:2.2.0'
compile 'com.squareup.retrofit2:converter-gson:2.2.0'
//rx+retrofit
compile 'com.squareup.retrofit2:adapter-rxjava2:2.2.0'
//rxjava
compile "io.reactivex.rxjava2:rxjava:2.0.8"
compile 'io.reactivex.rxjava2:rxandroid:2.0.1'
//rxbinding
compile 'com.jakewharton.rxbinding2:rxbinding:2.0.0'
compile 'com.jakewharton.rxbinding2:rxbinding-support-v4:2.0.0'
compile 'com.jakewharton.rxbinding2:rxbinding-appcompat-v7:2.0.0'
compile 'com.jakewharton.rxbinding2:rxbinding-design:2.0.0'
compile 'com.jakewharton.rxbinding2:rxbinding-recyclerview-v7:2.0.0'
2.创建观察者和被观察者
2.1创建获取观察者和被观察者的方法
//获取被观察者方法
public Observable<String> getObservable() {
return Observable.create(new ObservableOnSubscribe<String>() {
@Override
public void subscribe(@NonNull ObservableEmitter<String> e) throws Exception {
e.onNext("我是被观察者");
e.onComplete();
}
});
}
//获取观察者方法
public Observer<String> getObserver() {
return new Observer<String>() {
Disposable disposable = null;
@Override
public void onSubscribe(Disposable d) {
disposable = d;
}
@Override
public void onNext(String s) {
Log.e("onNext", s);
if (s.equals("取消关注")) {
//断开订阅
disposable.dispose();
}
}
@Override
public void onError(Throwable e) {
}
@Override
public void onComplete() {
Log.e("onComplete", "onComplete");
}
};
}
2.2初始化观察者和被观察者,并进行订阅操作
//拿到被观察者
Observable<String> observable = getObservable();
//拿到观察者
Observer<String> observer = getObserver();
//订阅
observable.subscribe(observer);
........这就是rxjava的简单使用了.........完全没有提到线程呢....下一章
网友评论