一、如何使用
在build.gradle中添加依赖
dependencies {
api 'io.reactivex:rxandroid:1.2.1'
api 'io.reactivex:rxjava:1.3.0'
implementation fileTree(include: ['*.jar'], dir: 'libs')
implementation 'com.android.support:appcompat-v7:27.1.1'
implementation 'com.android.support.constraint:constraint-layout:1.1.3'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.2'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
}
这里有一个小坑,直接用latest.release没有办法用,不知道为什么
二、代码实现
2.1 使用just+Action1+Action0来实现
Observable.just(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
.subscribeOn(Schedulers.io()) // Observable运行的线程
.observeOn(AndroidSchedulers.mainThread()) //监听者运行的线程
.subscribe(new Action1<Integer>() {
//onNext
@Override
public void call(Integer integer) {
log("call 1:" + integer);
}
}, new Action1<Throwable>() {
//onError
@Override
public void call(Throwable throwable) {
log("call 2");
}
}, new Action0() {
//onCompleted
@Override
public void call() {
log("call 3");
}
});
运行结果如下,很简单,就不一一解释了。
10-05 11:05:45.955 23619 23619 E MainActivity: yanlog msg:call 1:1
10-05 11:05:45.955 23619 23619 E MainActivity: yanlog msg:call 1:2
10-05 11:05:45.955 23619 23619 E MainActivity: yanlog msg:call 1:3
10-05 11:05:45.955 23619 23619 E MainActivity: yanlog msg:call 1:4
10-05 11:05:45.955 23619 23619 E MainActivity: yanlog msg:call 1:5
10-05 11:05:45.955 23619 23619 E MainActivity: yanlog msg:call 1:6
10-05 11:05:45.955 23619 23619 E MainActivity: yanlog msg:call 1:7
10-05 11:05:45.955 23619 23619 E MainActivity: yanlog msg:call 1:8
10-05 11:05:45.956 23619 23619 E MainActivity: yanlog msg:call 1:9
10-05 11:05:45.956 23619 23619 E MainActivity: yanlog msg:call 1:10
10-05 11:05:45.956 23619 23619 E MainActivity: yanlog msg:call 3
2.2 使用Just+Subscriber来实现
代码如下:
Observable.just(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
.subscribeOn(Schedulers.io()) // Observable运行的线程
.observeOn(AndroidSchedulers.mainThread()) //监听者运行的线程
.subscribe(new Subscriber<Integer>() {
@Override
public void onCompleted() {
log("onCompleted");
} @Override
public void onError(Throwable e) {
log("onError");
} @Override
public void onNext(Integer integer) {
log("onNext:" + integer);
}
});
运行结果如下:
10-05 19:56:09.991 982 982 E MainActivity: yanlog msg:onNext:1
10-05 19:56:09.991 982 982 E MainActivity: yanlog msg:onNext:2
10-05 19:56:09.991 982 982 E MainActivity: yanlog msg:onNext:3
10-05 19:56:09.992 982 982 E MainActivity: yanlog msg:onNext:4
10-05 19:56:09.992 982 982 E MainActivity: yanlog msg:onNext:5
10-05 19:56:09.992 982 982 E MainActivity: yanlog msg:onNext:6
10-05 19:56:09.992 982 982 E MainActivity: yanlog msg:onNext:7
10-05 19:56:09.992 982 982 E MainActivity: yanlog msg:onNext:8
10-05 19:56:09.992 982 982 E MainActivity: yanlog msg:onNext:9
10-05 19:56:09.992 982 982 E MainActivity: yanlog msg:onNext:10
10-05 19:56:09.992 982 982 E MainActivity: yanlog msg:onCompleted