This article mainly introduces relevant information about the new features of RxJava 2.x. The article introduces it in detail through pictures, texts and sample codes. It has certain reference value for everyone. Friends who need it can take a look below.
What is RxJava
Rx is asynchronous reactive ProgrammingThe essence isObserver mode , asynchronous reactive programming with observers and subscribers.
This article mainly introduces relevant information about the new features of RxJava 2.x. I won’t say much below, let’s take a look at the detailed introduction.
Backpressure separation
##Flowable/Subscriber
Flowable.range(0,10) .subscribe(new Subscriber<Integer>() { Subscription sub; //当订阅后,会首先调用这个方法,其实就相当于onStart(), //传入的Subscription s参数可以用于请求数据或者取消订阅 @Override public void onSubscribe(Subscription s) { Log.w("TAG","onsubscribe start"); sub=s; sub.request(1); Log.w("TAG","onsubscribe end"); } @Override public void onNext(Integer o) { Log.w("TAG","onNext--->"+o); sub.request(1); } @Override public void onError(Throwable t) { t.printStackTrace(); } @Override public void onComplete() { Log.w("TAG","onComplete"); } });
Output:
onsubscribe start onNext--->0 onNext--->1 onNext--->2 ... onNext--->10 onComplete onsubscribe endAs you can see from the output of the above code, when we call
subscription.request(n) method, the onNext method will be executed immediately before the code behind
onSubscribe() is executed. Therefore, if you use a class that needs to be initialized in the onNext method, you should try to
subscription.request(n) Do initialization work before calling this method;
Another creation method
Flowable.create(new FlowableOnSubscribe<Integer>() { @Override public void subscribe(FlowableEmitter<Integer> e) throws Exception { e.onNext(1); e.onNext(2); e.onNext(3); e.onNext(4); e.onComplete(); } } //需要指定背压策略 , BackpressureStrategy.BUFFER);
Other observations Pattern
//判断是否登陆 Maybe.just(isLogin()) //可能涉及到IO操作,放在子线程 .subscribeOn(Schedulers.newThread()) //取回结果传到主线程 .observeOn(AndroidSchedulers.mainThread()) .subscribe(new MaybeObserver<Boolean>() { @Override public void onSubscribe(Disposable d) { } @Override public void onSuccess(Boolean value) { if(value){ ... }else{ ... } } @Override public void onError(Throwable e) { } @Override public void onComplete() { } });In fact, this kind of observer The pattern is not used to send a large amount of data, but to send a single data. That is to say, when you only want the result (true or false) of a certain
event, you can use this observer pattern.
Action1——–ActionReference
#Summarize
The above is the detailed content of A graphic and text introduction summarizing the new features of RxJava 2.x. For more information, please follow other related articles on the PHP Chinese website!