Rxjava(1.基本使用)

1、rxjava

rxjava的本質

rxjava是響應式編程的意思,本質是觀察者模式,以觀察者observe和訂閱subscribe異步響應式開發。

RxJava is a Java VM implementation of Reactive Extensions: a library for composing asynchronous and event-based programs by using observable sequences.

rxjava的核心三步

依賴

 compile 'io.reactivex:rxjava:1.1.0'
 compile 'io.reactivex:rxandroid:1.1.0'

1、創建Observer(觀察者),如果通過訂閱後,被觀察者發生改變,觀察者做出相應的事件處理

 Subscriber<String> subscribers = new Subscriber<String>() {
        @Override
        public void onCompleted() {
        //完畢
        }
        @Override
        public void onError(Throwable e) {
        //發生異常
        }
        @Override
        public void onNext(String s) {
         //事件來了
        }
    };

2、創建Observables(被觀察者)

Observable observable = Observable.create(new Observable.OnSubscribe<String>() {

        @Override
        public void call(Subscriber<? super String> subscriber) {
            subscriber.onNext("hello rxjava");
        }
    });

3、subscribe 訂閱關係

 observable.subscribe(subscribers);

全部代碼如下:

package com.example.administrator.rxjavademo;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.TextView;

import rx.Observable;
import rx.Subscriber;

public class MainActivity extends AppCompatActivity {
    private TextView text;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        text= (TextView) findViewById(R.id.text);
        //確立訂閱關係,把訂閱(subscribers)事件加入到觀察者中(observable)
        observable.subscribe(subscribers);
    }
    //定義被觀察者,觀察對象對觀察者訂閱的Subscribe對象
    Observable observable = Observable.create(new Observable.OnSubscribe<String>() {

        @Override
        public void call(Subscriber<? super String> subscriber) {
            subscriber.onNext("hello rxjava");
        }
    });
    //觀察者,當觀察者事件改變時,訂閱者收到事件,處理事件
    Subscriber<String> subscribers = new Subscriber<String>() {
        @Override
        public void onCompleted() {

        }
        @Override
        public void onError(Throwable e) {
        }
        @Override
        public void onNext(String s) {
            text.setText(s);
        }
    };
}

2、線程切換

 @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Observable.create(new Observable.OnSubscribe<String>() {
            @Override
            public void call(Subscriber<? super String> subscriber) {
                subscriber.onNext("sss");
                Log.d("------->call線程:", Thread.currentThread().getName() + "");
            }
        }).subscribeOn(Schedulers.io()).
                observeOn(AndroidSchedulers.mainThread()).
                subscribe(new Subscriber<String>() {
            @Override
            public void onCompleted() {

            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onNext(String s) {
                Log.d("------->onNext線程:", Thread.currentThread().getName() + "");
            }
        });

運行結果:

------->call線程:: RxCachedThreadScheduler-1
------->onNext線程:: main

3、rxjava三步分析

1、Observable

 //定義被觀察者,被觀察對象與觀察者訂閱的Subscribe對象
    Observable observable = Observable.create(new Observable.OnSubscribe<String>() {

        @Override
        public void call(Subscriber<? super String> subscriber) {
            subscriber.onNext("hello rxjava");
        }
    });

這裏寫圖片描述


通過Observable類創建一個Observable對象,傳入的參數爲OnSubscribe,OnSubscribe繼承接口Action1
這裏寫圖片描述

2、Subscriber創建:通過new創建一個Subscriber對象

 Subscriber<String> subscribers = new Subscriber<String>() {
        @Override
        public void onCompleted() {

        }
        @Override
        public void onError(Throwable e) {
        }
        @Override
        public void onNext(String s) {
            text.setText(s);
        }
    };

Subscriber實現兩個接口,一個 Observer另一個 Subscription
源代碼如下:

public interface Observer<T> {

    /**
     * 觀察者發送事件結束
     */
    void onCompleted();

    /**
     *觀察者發送事件發生異常
     */
    void onError(Throwable e);

    /**
     *爲觀察者提供一個新的觀察項
     */
    void onNext(T t);

}

3、訂閱關係

 observable.subscribe(subscribers);

源代碼

//給觀察者訂閱事件,並給訂閱者一些方法的回調,比如事件完成,事件發生異常

  public final Subscription subscribe(Subscriber<? super T> subscriber) {
        return Observable.subscribe(subscriber, this);
    }

    private static <T> Subscription subscribe(Subscriber<? super T> subscriber, Observable<T> observable) {
     // validate and proceed
        if (subscriber == null) {
            throw new IllegalArgumentException("observer can not be null");
        }
        if (observable.onSubscribe == null) {
            throw new IllegalStateException("onSubscribe function can not be null.");
            /*
             * the subscribe function can also be overridden but generally that's not the appropriate approach
             * so I won't mention that in the exception
             */
        }

        // new Subscriber so onStart it
        subscriber.onStart();

        /*
         * See https://github.com/ReactiveX/RxJava/issues/216 for discussion on "Guideline 6.4: Protect calls
         * to user code from within an Observer"
         */
        // if not already wrapped
        if (!(subscriber instanceof SafeSubscriber)) {
            // assign to `observer` so we return the protected version
            subscriber = new SafeSubscriber<T>(subscriber);
        }

        // The code below is exactly the same an unsafeSubscribe but not used because it would 
        // add a significant depth to already huge call stacks.
        try {
            // allow the hook to intercept and/or decorate
            hook.onSubscribeStart(observable, observable.onSubscribe).call(subscriber);
            return hook.onSubscribeReturn(subscriber);
        } catch (Throwable e) {
            // special handling for certain Throwable/Error/Exception types
            Exceptions.throwIfFatal(e);
            // if an unhandled error occurs executing the onSubscribe we will propagate it
            try {
                subscriber.onError(hook.onSubscribeError(e));
            } catch (Throwable e2) {
                Exceptions.throwIfFatal(e2);
                // if this happens it means the onError itself failed (perhaps an invalid function implementation)
                // so we are unable to propagate the error correctly and will just throw
                RuntimeException r = new RuntimeException("Error occurred attempting to subscribe [" + e.getMessage() + "] and then again while trying to pass to onError.", e2);
                // TODO could the hook be the cause of the error in the on error handling.
                hook.onSubscribeError(r);
                // TODO why aren't we throwing the hook's return value.
                throw r;
            }
            return Subscriptions.unsubscribed();
        }
    }

3、Oberver與Subscriber關係

其中的Observer有一個具體的實現類 Subscriber,所以在開發中我們經常會使用Subscriber來代替Observer,所以在功能使用是二者是基本一樣的。

Observer與Subscriber的主要區別在於onCompleted()方法執行完畢後是否取消了訂閱。

Observer:在執行onCompleted()方法後沒有取消訂閱
Subscriber:在執行onCompleted()方法後取消訂閱,如果想要觸發事件的話,需要重新new 訂閱。

發佈了142 篇原創文章 · 獲贊 265 · 訪問量 23萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章