1. 程式人生 > >Rxjava,Scheduler執行緒變換的例子

Rxjava,Scheduler執行緒變換的例子

執行緒變換簡介

1.讓程式碼可以在不同的執行緒執行
2.subsribeOn——訂閱時的執行緒
3.observeOn——接收時的執行緒
4.Scheduler——實際做執行緒變換

匯入依賴

    def retrofit_version = "2.1.0"
    def rxjava_version = "2.0.1"

    //RxJava的依賴包
    implementation 'io.reactivex.rxjava2:rxjava:' + rxjava_version
    //RxAndroid的依賴包
    implementation 'io.reactivex.rxjava2:rxandroid:' + rxjava_version

    //RxBinding
    implementation 'com.jakewharton.rxbinding2:rxbinding:2.1.1'

例子

Observable
                .create(new ObservableOnSubscribe<String>() {
                    @Override
                    public void subscribe(ObservableEmitter<String> e) throws Exception {
                        Log.d(TAG, "subscribe: "+Thread.currentThread());
                        e.onNext("1");
                        e.onNext("2");
                        e.onNext("3");
                    }
                })
                .subscribeOn(Schedulers.newThread())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<String>() {
                    @Override
                    public void accept(String s) throws Exception {
                        Log.d(TAG, "accept: "+Thread.currentThread());
                        Log.d(TAG, "accept: "+s);
                    }
                });

輸出

2018-12-04 21:57:58.936 26114-26142/? D/MainActivity: subscribe: Thread[RxNewThreadScheduler-1,5,main]
2018-12-04 21:57:58.959 26114-26114/? D/MainActivity: accept: Thread[main,5,main]
2018-12-04 21:57:58.959 26114-26114/? D/MainActivity: accept: 1
2018-12-04 21:57:58.959 26114-26114/? D/MainActivity: accept: Thread[main,5,main]
2018-12-04 21:57:58.959 26114-26114/? D/MainActivity: accept: 2
2018-12-04 21:57:58.959 26114-26114/? D/MainActivity: accept: Thread[main,5,main]
2018-12-04 21:57:58.959 26114-26114/? D/MainActivity: accept: 3