This tutorial is a comprehensive explanation based on the RxJava1.x version. Subsequent courses will be updated one after another, so stay tuned...
The following functions are all functions used to create the observed Observable. We can create corresponding functions as needed.
Create - The original Observable creation function
Defer - An Observable created after creating a subscription
Empty/Never/Throw - Create an Observable that sends no data/to send data with an exception
Just - Create an Observable that sends 1-9 values
From - Create an Observable that emits a queue
Interval&Timer - Create an Observable similar to a timer
Range - Create an Observable that emits a specific integer type
Repeat - Create an Observable that sets the number of repeated emits
You can use the Create operator to create an Observable from scratch, pass this operator a function that accepts an observer as a parameter, and write this function to behave like an Observable - appropriately call the observer's onNext, onError and onCompleted method.
A properly formed finite Observable must attempt to call the observer's onCompleted exactly once or its onError exactly once, and may not call any other methods of the observer thereafter.
It is recommended that you check the isUnsubscribed status of the observer in the function passed to the create method, so that your Observable can stop emitting data or doing expensive operations when there are no observers.
Sample code:
Observable.create(new Observable.OnSubscribe<Integer>() { @Override public void call(Subscriber<? super Integer> observer) { try { if (!observer.isUnsubscribed()) { for (int i = 1; i < 5; i++) { observer.onNext(i); } observer.onCompleted(); } } catch (Exception e) { observer.onError(e); } } } ).subscribe(new Subscriber<Integer>() { @Override public void onNext(Integer item) { System.out.println("Next: " + item); } @Override public void onError(Throwable error) { System.err.println("Error: " + error.getMessage()); } @Override public void onCompleted() { System.out.println("Sequence complete."); } });
Output:
Next: 1 Next: 2 Next: 3 Next: 4 Sequence complete.
The Observable is not created until an observer subscribes, and for each observer Create a new Observable.
The Defer operator waits until an observer subscribes to it, and then it uses the Observable factory method to generate an Observable. It does this for every Observer, so even though each subscriber thinks they are subscribing to the same Observable, in fact each subscriber is getting their own separate sequence of data.
The code is as follows:
Observable<String> defer = Observable.defer(new Func0<Observable<String>>() { //当observable被创建的时候顺便调用observable内部的call()方法并在方法中发送消息 //每subscribe()就会在call()中返回一个新的实例对象 @Override public Observable<String> call() { Observable<String> observable = Observable.create(new Observable.OnSubscribe<String>() { @Override public void call(Subscriber<? super String> subscriber) { subscriber.onNext("Hello Android !"); } }); return observable; } }); defer.subscribe(new Action1<String>() { @Override public void call(String s) { } }); defer.subscribe(new Action1<String>() { @Override public void call(String s) { } });
Create an Observable that does not emit any data but terminates normally
Create an Observable that does not emit data and terminates with an error
Create an Observable that does not emit data and terminates with an error
The behavior of the Observable generated by these three operators is very special and restricted. It is useful for testing, and sometimes used in combination with other Observables, or as parameters of other operators that require Observables.
RxJava implements these operators as empty, never and error. The error operator requires a Throwable parameter, with which your Observable will terminate. These operators do not execute on any specific scheduler by default, but empty and error have an optional parameter called Scheduler. If you pass the Scheduler parameter, they will send notifications on this scheduler.
If the observer wants to emit data to the observer, the code is as follows:
Observable .create(new Observable.OnSubscribe<String>() { @Override public void call(Subscriber<? super String> subscriber) { subscriber.onNext("hello Android"); } }) .subscribe(new Action1<String>() { @Override public void call(String s) { Log.i(TAG, "call: "+s); } });
If the above code wants to send data, it must first implement Observable .OnSubscribe interface, we can use just function instead. The sample code is as follows:
Observable .just("hello Android") .subscribe(new Action1<String>() { @Override public void call(String s) { Log.i(TAG, "call: "+s); } });
Output:
onNext: hello Android Sequence complete.
Just convert a single data into an Observable that emits that data.
Similar functions are:
public static class Student { public String name; public int age; public Student(String name, int age) { this.name = name; this.age = age; } @Override public String toString() { return "Student{" + "name='" + name + '\'' + ", age=" + age + '}'; } }
private ArrayList initPersons() { ArrayList<Student> persons = new ArrayList<>(); persons.add(new Student("张三", 16)); persons.add(new Student("李四", 17)); persons.add(new Student("王二麻子", 18)); return persons; }
ArrayList persons = initPersons(); for (int i = 0; i < persons.size(); i++) { //打印每个同学 Log.i(TAG,persons.get(i).toString()); }
//1.定义被观察者,用来发送一个队列的事件 Observable<Student> observable = Observable.from(persons); //2.当开始订阅的时候 接收被观察者发送过来的一系列事件 observable.subscribe(new Action1<Student>() { @Override public void call(Student student) { Log.i(TAG, "call: "+student.toString()); } });
//3000毫米发送一个请求 该请求包含了一个自增长的整数型变量 Observable<Long> observable = Observable.interval(3000, TimeUnit.MILLISECONDS, Schedulers.io()); observable.subscribe(new Action1<Long>() { @Override public void call(Long i) { // such as printf RxIoScheduler-2call: 685 Log.i(TAG, Thread.currentThread().getName()+"call: "+i); } });
com.m520it.rxjava I/IT520: RxIoScheduler-2call: 0 com.m520it.rxjava I/IT520: RxIoScheduler-2call: 1 com.m520it.rxjava I/IT520: RxIoScheduler-2call: 2 com.m520it.rxjava I/IT520: RxIoScheduler-2call: 3 ...
Observable<Long> timer = Observable.timer(3000, 2000, TimeUnit.MILLISECONDS); timer.subscribe(new Action1<Long>() { @Override public void call(Long aLong) { Log.i(TAG, "call: "+aLong); } });
比如下面这个班级的所有学生都在一个集合里,现在要打印出来,可以是这样的:
private ArrayList initPersons() { ArrayList<Student> persons = new ArrayList<>(); persons.add(new Student("张三", 16)); persons.add(new Student("李四", 17)); persons.add(new Student("王二麻子", 18)); return persons; } final ArrayListstudents = initPersons(); //这里发射一个起始值0,长度students.size()的索引 用来遍历队列 Observable .range(0,students.size()) .subscribe(new Action1 () { @Override public void call(Integer index) { Log.i(TAG, "call: "+students.get(index)); } });
创建一个发射特定数据重复多次的Observable
Repeat重复地发射数据。某些实现允许你重复的发射某个数据序列,还有一些允许你限制重复的次数。
//设置重复发送3次 Observable<String> observable = Observable.just("Hello Android").repeat(3); Action1<String> action1 = new Action1<String>() { @Override public void call(String s) { Log.i(TAG, "call: " + s); } }; observable.subscribe(action1);
以上就是深入浅出RxJava_03[被观察者创建操作]的详细介绍的内容,更多相关内容请关注PHP中文网(m.sbmmt.com)!