初探RxJava


首先到底什麼是RxJava,RxJava是一個相應式編程框架,採用觀察者模式,既然使用觀察者模式,就一定少不了觀察者和被觀察者。

RxJava 是一個開源項目,地址:https://github.com/ReactiveX/RxJava。

還有一個RxAndroid,用於 Android 開發,添加了 Android 用的接口。地址:https://github.com/ReactiveX/RxAndroid。(其實看他的Observable給我一種和Volley用法相似的感覺。。)

轉載地址:http://www.cnblogs.com/halzhang/p/4458095.html。

RxJava資料參考:http://blog.piasy.com/AdvancedRxJava/2016/05/06/operator-concurrency-primitives/。

例子

通過請求openweathermap 的天氣查詢接口返回天氣數據

1、增加編譯依賴

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile 'com.android.support:appcompat-v7:22.0.0'
    compile 'io.reactivex:rxjava:1.0.9'
    compile 'io.reactivex:rxandroid:0.24.0'
    compile 'com.squareup.retrofit:retrofit:1.9.0'
}

retrofit 是一個 restful 請求客戶端。詳見:http://square.github.io/retrofit/

2、服務器接口

/**
 * 接口
 * Created by Hal on 15/4/26.
 */
public class ApiManager {

    private static final String ENDPOINT = "http://api.openweathermap.org/data/2.5";

    /**
     * 服務接口
     */
    private interface ApiManagerService {
        @GET("/weather")
        WeatherData getWeather(@Query("q") String place, @Query("units") String units);
    }

    private static final RestAdapter restAdapter = new RestAdapter.Builder().setEndpoint(ENDPOINT).setLogLevel(RestAdapter.LogLevel.FULL).build();

    private static final ApiManagerService apiManager = restAdapter.create(ApiManagerService.class);

    /**
     * 將服務接口返回的數據,封裝成{@link rx.Observable}
     * @param city
     * @return
     */
    public static Observable<WeatherData> getWeatherData(final String city) {
        return Observable.create(new Observable.OnSubscribe<WeatherData>() {
            @Override
            public void call(Subscriber<? super WeatherData> subscriber) {
                //訂閱者回調 onNext 和 onCompleted
                subscriber.onNext(apiManager.getWeather(city, "metric"));
                subscriber.onCompleted();
            }
        }).subscribeOn(Schedulers.io());
    }
}
3、接口調用

/**
         * 多個 city 請求
         * map,flatMap 對 Observable進行變換
         */
        Observable.from(CITIES).flatMap(new Func1<String, Observable<WeatherData>>() {
            @Override
            public Observable<WeatherData> call(String s) {
                return ApiManager.getWeatherData(s);
            }
        }).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(/*onNext*/new Action1<WeatherData>() {
                    @Override
                    public void call(WeatherData weatherData) {
                        Log.d(LOG_TAG, weatherData.toString());
                    }
                }, /*onError*/new Action1<Throwable>() {
                    @Override
                    public void call(Throwable throwable) {

                    }
                });

        /**
         * 單個 city 請求
         */
        ApiManager.getWeatherData(CITIES[0]).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<WeatherData>() {
                    @Override
                    public void call(WeatherData weatherData) {
                        Log.d(LOG_TAG, weatherData.toString());
                        ((TextView) findViewById(R.id.text)).setText(weatherData.toString());
                    }
                }, new Action1<Throwable>() {
                    @Override
                    public void call(Throwable throwable) {
                        Log.e(LOG_TAG, throwable.getMessage(), throwable);
                    }
                });

        /**
         * Android View 事件處理
         */
        ViewObservable.clicks(findViewById(R.id.text), false).subscribe(new Action1<OnClickEvent>() {
            @Override
            public void call(OnClickEvent onClickEvent) {

            }
        });
 subscribeOn(Schedulers.io())與observeOn(AndroidSchedulers.mainThread())分別定義了這兩個動作的線程。Android UI 更新需要在主線程。


4、retrofit 支持 rxjava 整合

/**
     * 服務接口
     */
    private interface ApiManagerService {
        @GET("/weather")
        WeatherData getWeather(@Query("q") String place, @Query("units") String units);

        /**
         * retrofit 支持 rxjava 整合
         * 這種方法適用於新接口
         */
        @GET("/weather")
        Observable<WeatherData> getWeatherData(@Query("q") String place, @Query("units") String units);
    }
個人感覺原文對RxJava的簡單用法已經使用和解釋的比較清楚了,電腦沒電了先轉過來,明天我會按照自己的理解重新寫一個demo。(看到retrofit讓想起了之前使用android annotations的感覺。。)


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章