Rxjava2之rxandroid基本用法
阿新 • • 發佈:2019-01-09
compile 'io.reactivex.rxjava2:rxandroid:2.0.1'
compile 'io.reactivex.rxjava2:rxjava:2.0.5'
- 1
- 2
- 3
這裡主要介紹基本的使用以及Action和Function的一些變動
以下是RxJava的標準使用
private void normalCreate() {
//建立觀察者,subscriber或observer
Observer<String> observer=new Observer<String>() {
@Override
/**
* Provides the Observer with the means of cancelling (disposing) the
* connection (channel) with the Observable in both
* synchronous (from within {@link #onNext(Object)}) and asynchronous manner.
* @param d the Disposable instance whose {@link Disposable#dispose()} can
* be called anytime to cancel the connection
* @since 2.0
*/
public void onSubscribe(Disposable d) {
//可用於取消訂閱
d.dispose();
//還可以判斷是否處於取消狀態
//boolean b=d.isDisposed();
}
//一般需要展示
@Override
public void onNext(String s) {
Log.e("TAG", "onNext: "+s );
}
@Override
public void onError(Throwable e) {
}
@Override
public void onComplete() {
}
};
//建立被觀察者
//和RxJava1.0相比,他們都增加了throws Exception,也就是說,在這些方法做某些操作就不需要try-catch 。
Observable<String> observable=Observable.create(new ObservableOnSubscribe<String>() {
@Override
//將事件發射出去,持有觀察者的物件
public void subscribe(ObservableEmitter<String> e) throws Exception {
e.onNext("第一次呼叫");
e.onNext("第二次呼叫");
e.onNext("第三次呼叫");
e.onComplete();
}
});
//確立訂閱關係
observable.subscribe(observer);
}
- 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
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
private void mapDemo() {
//在2.0後命名規則有了改變
//Action1--------Consumer一個引數的
//Action2--------BiConsumer兩個引數的
//而Function的也一樣
Observable.just("圖片存放路徑").map(new Function<String, Bitmap>() {
@Override
public Bitmap apply(String s) throws Exception {
return getBitmapFromFile(s);
}
}).subscribeOn(Schedules.io())//指定 subscribe() 事件傳送發生在 IO 執行緒
.observeOn(AndroidSchedulers.mainThread())//指定 Subscriber 的回撥處理髮生在主執行緒
//這裡的Action一個引數的改為COnsumer
.subscribe(new Consumer<Bitmap>() {
@Override
public void accept(Bitmap bitmap) throws Exception {
iv.setImageBitmap(bitmap);
}
});
}