RxJava

前言

RxJava 的观察者模式大致如下图:

RxJava_第1张图片

RxJava 还内置了一个实现了 Observer 的抽象类:Subscriber。

开始之前请进行gradle的配置

/rxjava/

compile 'io.reactivex:rxjava:1.1.3'

compile 'io.reactivex:rxandroid:1.0.1'

/rxjava的混淆/

compile 'com.artemzin.rxjava:proguard-rules:1.1.3.0'
compile 'com.squareup.retrofit2:converter-gson:2.0.0-beta3'
compile 'com.squareup.retrofit2:retrofit:2.0.0-beta3'
compile 'com.squareup.retrofit2:adapter-rxjava:2.0.0-beta3'


使用特性详解

1.线程切换Scheduler

subscribeOn() 和 observeOn() 两个方法来对线程进行控制

subscribeOn(): 指定 subscribe() 所发生的线程,即 Observable.OnSubscribe 被激活时所处的线程。或者叫做事件产生的线程。
observeOn(): 指定 Subscriber 所运行在的线程。或者叫做事件消费的线程。

示例:

Observable.just(1, 2, 3, 4) // IO 线程,由 subscribeOn() 指定
//被创建的事件的内容 1、2、3、4 将会在 IO 线程发出
.subscribeOn(Schedulers.io())
.observeOn(Schedulers.newThread())
.map(new Func1() {
    @Override
    public String call(Integer integer) {
        Log.e(TAG, Thread.currentThread().getName() + "Schedulers.newThread()");
        return "call" + integer;
    }
}) // 新线程,由 observeOn() 指定
.observeOn(Schedulers.io())
.map(new Func1() {
    @Override
    public Integer call(String s) {
        Log.i(TAG, Thread.currentThread().getName() + "Schedulers.io()");

        final char[] chars = s.toCharArray();
        int res = -1;
        for (char c : chars) {
            res += c;
        }
        return res;
    }
}) // 指定 Subscriber 的回调发生在主线程
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Subscriber() {   // Android 主线程,由 observeOn() 指定
    @Override
    public void onCompleted() {
        Log.d(TAG, "Thread:" + Thread.currentThread().toString() + "->onCompleted");
    }

    @Override
    public void onError(Throwable e) {
        Log.d(TAG, "Thread:" + Thread.currentThread().toString() + "->onError:" + e.toString());
    }

    @Override
    public void onNext(Integer integer) {
        Log.d(TAG, "Thread:" + Thread.currentThread().toString() + "->onNext:" + integer);
    }
});

经历了两次变换,int->String ;String->int;然后提交。

RxJava_第2张图片
Paste_Image.png

2.变换
a.一对一,map
List lists = new ArrayList<>();
lists.add(new Student(10, "jack", Arrays.asList("数学", "语文", "英语")));
lists.add(new Student(20, "helen", Arrays.asList("物理", "化学")));
lists.add(new Student(30, "alice", Arrays.asList("生物", "地理")));

Observable.from(lists)
        .subscribeOn(Schedulers.io())
        .observeOn(AndroidSchedulers.mainThread())
        .map(new Func1() {
            @Override
            public Integer call(Student student) {
                try {
                    Log.d(TAG, "Thread:" + Thread.currentThread().toString() + "->call:" + student.toString());
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                return student.getAge();
            }
        })
        .subscribe(new Action1() {
            @Override
            public void call(Integer integer) {
                Log.d(TAG, "Thread:" + Thread.currentThread().toString() + "->call:" + integer);
            }
        });
Paste_Image.png
b.一对多,flatmap
List lists = new ArrayList<>();
lists.add(new Student(10, "jack", Arrays.asList("数学", "语文", "英语")));
lists.add(new Student(20, "helen", Arrays.asList("物理", "化学")));
lists.add(new Student(30, "alice", Arrays.asList("生物", "地理")));

Observable.from(lists)
        .subscribeOn(Schedulers.io())               // 被创建的事件的内容 1、2、3、4 将会在 IO 线程发出,也叫事件产生的线程
        .observeOn(AndroidSchedulers.mainThread())  // 指定 Subscriber 的回调发生在主线程,也叫事件消费的线程
        .flatMap(new Func1>() {
            @Override
            public Observable call(Student student) {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                return Observable.from(student.getCourses());
            }
        })
        .subscribe(new Subscriber() {
            @Override
            public void onCompleted() {
                Log.d(TAG, "Thread:" + Thread.currentThread().toString() + "->onCompleted");
            }

            @Override
            public void onError(Throwable e) {
                Log.d(TAG, "Thread:" + Thread.currentThread().toString() + "->onError:" + e.toString());
            }

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

打印所有学生的课程

RxJava_第3张图片
Paste_Image.png
c.对 Observable自身变换,compose

Transformer实际上就是一个Func1, Observable>
换言之就是:可以通过它将一种类型的Observable转换成另一种类型的Observable。

Observable.Transformer myTransformer = new Observable.Transformer() {
    @Override
    public Observable call(Observable observable) {
        return observable
                .map(new Func1() {
                    @Override
                    public String call(Integer integer) {
                        String info = "myTransforer:" + integer;
                        Log.i(TAG, "转换Obserable->Thread:" + Thread.currentThread().toString() + "->call:" + info);
                        return info;
                    }
                });
    }
};
Observable.just(1, 2, 3).compose(myTransformer)
        .subscribe(new Action1() {
            @Override
            public void call(String s) {
                Log.d(TAG, "Thread:" + Thread.currentThread().toString() + "->call:" + s);
            }
        });
Paste_Image.png

3.过滤 Filter

查找,学生中学习语文的同学的名字.

List lists = new ArrayList<>();
lists.add(new Student(10, "jack", Arrays.asList("数学", "语文", "英语")));
lists.add(new Student(20, "helen", Arrays.asList("物理", "化学", "语文")));
lists.add(new Student(30, "alice", Arrays.asList("生物", "地理")));

Observable.from(lists)
        .subscribeOn(Schedulers.io())
        .observeOn(AndroidSchedulers.mainThread())
        .filter(new Func1() {
            @Override
            public Boolean call(Student student) {
                return student.getCourses().contains("语文");
            }
        }).subscribe(new Subscriber() {
            @Override
            public void onCompleted() {
                Log.d(TAG, "Thread:" + Thread.currentThread().toString() + "->onCompleted");
            }

            @Override
            public void onError(Throwable e) {
                Log.d(TAG, "Thread:" + Thread.currentThread().toString() + "->onError:" + e.toString());
            }

            @Override
            public void onNext(Student s) {
                Log.d(TAG, "Thread:" + Thread.currentThread().toString() + "->onNext:" + s.getName());
            }
        });
Paste_Image.png

4.Retrofit & RxJava

添加依赖

compile 'com.squareup.retrofit2:converter-gson:2.0.0-beta3'
compile 'com.squareup.retrofit2:retrofit:2.0.0-beta3'
compile 'com.squareup.retrofit2:adapter-rxjava:2.0.0-beta3'

private Subscription subscription;

public void onRetrofit(View view) throws IOException {
    final GithubApi GithubApi = GithubService.createGithubService();

    //第一种,自己创建子线程请求
//        final Call> call = GithubApi.getGroupList("square", "retrofit");
//        new Thread(){
//            @Override
//            public void run() {
//                final Response> execute;
//                try {
//                    //网络请求不能再主线程
//                    execute = call.execute();
//                    final List constructors = execute.body();
//                    for (Constructor constructor : constructors){
//                        Log.d(TAG, constructor.toString());
//                    }
//                } catch (IOException e) {
//                    e.printStackTrace();
//                }
//            }
//        }.start();

    /**
     * 方法二,通过RxJava,进行线程的切换
     * 1.Retrofit的配置需要改 .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
     * 2.接口需要改
     * Observable> contributorsRx(@Path("owner") String owner, @Path("repo") String repo);
     * 3.需要在 Activity的onDestroy方法解注册
     */

    subscription = GithubApi.contributorsRx("square", "retrofit")
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(new Subscriber>() {
                @Override
                public void onCompleted() {

                }

                @Override
                public void onError(Throwable e) {

                }

                @Override
                public void onNext(List constructors) {
                    for (Constructor constructor : constructors) {
                        Log.d(TAG, constructor.toString());
                    }
                }
            });

}

@Override
protected void onDestroy() {
    super.onDestroy();
    if (subscription != null) {
        subscription.unsubscribe();
    }
}
Paste_Image.png

附上

public interface GithubApi {
    @GET("/repos/{owner}/{repo}/contributors")
    Call> getGroupList(@Path("owner") String owner, @Path("repo") String repo);

    @GET("/repos/{owner}/{repo}/contributors")
    Observable> contributorsRx(@Path("owner") String owner, @Path("repo") String repo);
}

public class GithubService {

    public static GithubApi createGithubService() {
        Retrofit.Builder builder = new Retrofit.Builder()
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .addConverterFactory(GsonConverterFactory.create())
                .baseUrl("https://api.github.com");

        return builder.build().create(GithubApi.class);

    }
}

5.RxJava replace AsyncTask
/*new AsyncTask() {
    @Override
    protected User doInBackground(String... params) {
        return _githubService.getUser(params[0]);
    }

    @Override
    protected void onPostExecute(User user) {
        _adapter.add(format("%s  = [%s: %s]", _username.getText(), user.name, user.email));
    }
}.execute(_username.getText().toString());*/

_githubService.user(_username.getText().toString())
      .subscribeOn(Schedulers.io())
      .observeOn(AndroidSchedulers.mainThread())
      .subscribe(new Observer() {
          @Override
          public void onCompleted() {
          }

          @Override
          public void onError(Throwable e) {
          }

          @Override
          public void onNext(User user) {
              _adapter.add(format("%s  = [%s: %s]",
                    _username.getText(),
                    user.name,
                    user.email));
          }
      });

示例代码路径: Jack_Rxjava_demo

参考资料

  • 给 Android 开发者的 RxJava 详解

你可能感兴趣的:(RxJava)