RxJava常用功能

精彩推荐:给 Android 开发者的 RxJava 详解

//RxJava 有2个最基本概念:Observable (可观察者,即被观察者)、 Observer (观察者)

1.创建Observable对象

Observable myObservable = Observable.create(new Observable.OnSubscribe() {
    @Override
    public void call(Subscribersuper String> subscriber) {

    }
});

2.简洁代码创建Observable对象

Observable<String> myObservable2 = Observable.just("Hello, world!");

3.单事件处理

Action1 onNextAction = new Action1() {
    @Override
    public void call(String s) {
        System.out.println(s);
    }
};

myObservable2.subscribe(onNextAction);

3.单事件处理(简洁)

Observable.just("").subscribe(new Action1() {
    @Override
    public void call(String s) {

    }
});

4.map操作符,把一个事件转化成另一个事件

Observable.just("").map(new Func1<String, Integer>() {
    @Override
    public Integer call(String s) {
        return s.hashCode();
    }
}).subscribe(new Action1<Integer>() {
    @Override
    public void call(Integer integer) {

    }
});

5.from接收一个集合作为输入,然后每次输出一个元素给subscriber

Observable<List<String>> query(String text);
final String[] urls = new String[]{"1", "2", "3"};

//本来要这么写
query("").subscribe(new Action1>() {
    @Override
    public void call(List strings) {
        for (String url : urls) {
            Log.v("-->", url);
        }
    }
});

//现在这么写
query("").subscribe(new Action1>() {
    @Override
    public void call(List strings) {
        Observable.from(urls).subscribe(new Action1() {
            @Override
            public void call(String s) {
                Log.v("-->", s);
            }
        });
    }
});

6.flatMap实现一对多的转化

Student[] students = ...;
Subscriber subscriber = new Subscriber() {
    @Override
    public void onNext(Course course) {
        Log.d(tag, course.getName());
    }
    ...
};
Observable.from(students)
    .flatMap(new Func1>() {
        @Override
        public Observable call(Student student) {
            return Observable.from(student.getCourses());
        }
    })
    .subscribe(subscriber);

你可能感兴趣的:(RxJava常用功能)