本文轉載自:html
http://blog.csdn.net/theone10211024/article/details/50435325java
1、Scheduler線程切換數組
這種場景常常會在「後臺線程取數據,主線程展現」的模式中看見緩存
- Observable.just(1, 2, 3, 4)
- .subscribeOn(Schedulers.io()) // 指定 subscribe() 發生在 IO 線程
- .observeOn(AndroidSchedulers.mainThread()) // 指定 Subscriber 的回調發生在主線程
- .subscribe(new Action1<Integer>() {
- @Override
- public void call(Integer number) {
- Log.d(tag, "number:" + number);
- }
- });
2、使用debounce作textSearch網絡
用簡單的話講就是當N個結點發生的時間太靠近(即發生的時間差小於設定的值T),debounce就會自動過濾掉前N-1個結點。app
好比在作百度地址聯想的時候,可使用debounce減小頻繁的網絡請求。避免每輸入(刪除)一個字就作一次聯想框架
- RxTextView.textChangeEvents(inputEditText)
- .debounce(400, TimeUnit.MILLISECONDS)
- .observeOn(AndroidSchedulers.mainThread())
- .subscribe(new Observer<TextViewTextChangeEvent>() {
- @Override
- public void onCompleted() {
- log.d("onComplete");
- }
-
- @Override
- public void onError(Throwable e) {
- log.d("Error");
- }
-
- @Override
- public void onNext(TextViewTextChangeEvent onTextChangeEvent) {
- log.d(format("Searching for %s", onTextChangeEvent.text().toString()));
- }
- });
3、Retrofit結合RxJava作網絡請求框架
這裏不做詳解,具體的介紹能夠看扔物線的這篇文章,對RxJava的入門者有很大的啓發。其中也講到了RxJava和Retrofit如何結合來實現更簡潔的代碼
4、RxJava代替EventBus進行數據傳遞:RxBus
注意:RxBus並非一個庫,而是一種模式,是使用了RxJava的思想來達到EventBus的數據傳遞效果。這篇文章把RxBus講的比較詳細。
5、使用combineLatest合併最近N個結點
例如:註冊的時候全部輸入信息(郵箱、密碼、電話號碼等)合法才點亮註冊按鈕。
- Observable<CharSequence> _emailChangeObservable = RxTextView.textChanges(_email).skip(1);
- Observable<CharSequence> _passwordChangeObservable = RxTextView.textChanges(_password).skip(1);
- Observable<CharSequence> _numberChangeObservable = RxTextView.textChanges(_number).skip(1);
-
- Observable.combineLatest(_emailChangeObservable,
- _passwordChangeObservable,
- _numberChangeObservable,
- new Func3<CharSequence, CharSequence, CharSequence, Boolean>() {
- @Override
- public Boolean call(CharSequence newEmail,
- CharSequence newPassword,
- CharSequence newNumber) {
-
- Log.d("xiayong",newEmail+" "+newPassword+" "+newNumber);
- boolean emailValid = !isEmpty(newEmail) &&
- EMAIL_ADDRESS.matcher(newEmail).matches();
- if (!emailValid) {
- _email.setError("Invalid Email!");
- }
-
- boolean passValid = !isEmpty(newPassword) && newPassword.length() > 8;
- if (!passValid) {
- _password.setError("Invalid Password!");
- }
-
- boolean numValid = !isEmpty(newNumber);
- if (numValid) {
- int num = Integer.parseInt(newNumber.toString());
- numValid = num > 0 && num <= 100;
- }
- if (!numValid) {
- _number.setError("Invalid Number!");
- }
-
- return emailValid && passValid && numValid;
-
- }
- })//
- .subscribe(new Observer<Boolean>() {
- @Override
- public void onCompleted() {
- log.d("completed");
- }
-
- @Override
- public void onError(Throwable e) {
- log.d("Error");
- }
-
- @Override
- public void onNext(Boolean formValid) {
- _btnValidIndicator.setEnabled(formValid);
- }
- });
6、使用merge合併兩個數據源。ide
例如一組數據來自網絡,一組數據來自文件,須要合併兩組數據一塊兒展現。post
- Observable.merge(getDataFromFile(), getDataFromNet())
- .observeOn(AndroidSchedulers.mainThread())
- .subscribe(new Subscriber<String>() {
- @Override
- public void onCompleted() {
- log.d("done loading all data");
- }
-
- @Override
- public void onError(Throwable e) {
- log.d("error");
- }
-
- @Override
- public void onNext(String data) {
- log.d("all merged data will pass here one by one!")
- });
7、使用concat和first作緩存this
依次檢查memory、disk和network中是否存在數據,任何一步一旦發現數據後面的操做都不執行。
- Observable<String> memory = Observable.create(new Observable.OnSubscribe<String>() {
- @Override
- public void call(Subscriber<? super String> subscriber) {
- if (memoryCache != null) {
- subscriber.onNext(memoryCache);
- } else {
- subscriber.onCompleted();
- }
- }
- });
- Observable<String> disk = Observable.create(new Observable.OnSubscribe<String>() {
- @Override
- public void call(Subscriber<? super String> subscriber) {
- String cachePref = rxPreferences.getString("cache").get();
- if (!TextUtils.isEmpty(cachePref)) {
- subscriber.onNext(cachePref);
- } else {
- subscriber.onCompleted();
- }
- }
- });
-
- Observable<String> network = Observable.just("network");
-
- //依次檢查memory、disk、network
- Observable.concat(memory, disk, network)
- .first()
- .subscribeOn(Schedulers.newThread())
- .subscribe(s -> {
- memoryCache = "memory";
- System.out.println("--------------subscribe: " + s);
- });
8、使用timer作定時操做。當有「x秒後執行y操做」相似的需求的時候,想到使用timer
例如:2秒後輸出日誌「hello world」,而後結束。
- Observable.timer(2, TimeUnit.SECONDS)
- .subscribe(new Observer<Long>() {
- @Override
- public void onCompleted() {
- log.d ("completed");
- }
-
- @Override
- public void onError(Throwable e) {
- log.e("error");
- }
-
- @Override
- public void onNext(Long number) {
- log.d ("hello world");
- }
- });
9、使用interval作週期性操做。當有「每隔xx秒後執行yy操做」相似的需求的時候,想到使用interval
例如:每隔2秒輸出日誌「helloworld」。
- Observable.interval(2, TimeUnit.SECONDS)
- .subscribe(new Observer<Long>() {
- @Override
- public void onCompleted() {
- log.d ("completed");
- }
-
- @Override
- public void onError(Throwable e) {
- log.e("error");
- }
-
- @Override
- public void onNext(Long number) {
- log.d ("hello world");
- }
- });
10、使用throttleFirst防止按鈕重複點擊
ps:debounce也能達到一樣的效果
- RxView.clicks(button)
- .throttleFirst(1, TimeUnit.SECONDS)
- .subscribe(new Observer<Object>() {
- @Override
- public void onCompleted() {
- log.d ("completed");
- }
-
- @Override
- public void onError(Throwable e) {
- log.e("error");
- }
-
- @Override
- public void onNext(Object o) {
- log.d("button clicked");
- }
- });
11、使用schedulePeriodically作輪詢請求
- Observable.create(new Observable.OnSubscribe<String>() {
- @Override
- public void call(final Subscriber<? super String> observer) {
-
- Schedulers.newThread().createWorker()
- .schedulePeriodically(new Action0() {
- @Override
- public void call() {
- observer.onNext(doNetworkCallAndGetStringResult());
- }
- }, INITIAL_DELAY, POLLING_INTERVAL, TimeUnit.MILLISECONDS);
- }
- }).subscribe(new Action1<String>() {
- @Override
- public void call(String s) {
- log.d("polling….」));
- }
- })
12、RxJava進行數組、list的遍歷
- String[] names = {"Tom", "Lily", "Alisa", "Sheldon", "Bill"};
- Observable
- .from(names)
- .subscribe(new Action1<String>() {
- @Override
- public void call(String name) {
- log.d(name);
- }
- });
十3、解決嵌套回調(callback hell)問題
- NetworkService.getToken("username", "password")
- .flatMap(s -> NetworkService.getMessage(s))
- .subscribe(s -> {
- System.out.println("message: " + s);
- })
十4、響應式的界面
好比勾選了某個checkbox,自動更新對應的preference
- SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
- RxSharedPreferences rxPreferences = RxSharedPreferences.create(preferences);
-
- Preference<Boolean> checked = rxPreferences.getBoolean("checked", true);
-
- CheckBox checkBox = (CheckBox) findViewById(R.id.cb_test);
- RxCompoundButton.checkedChanges(checkBox)
- .subscribe(checked.asAction());