preface

Finally, RxJava, an open source library that I personally love, is a great combination of chained programming style and asynchracy. RxJava actually already for a long time, is already very fire, but at present there are still quite a number of Android developer has not used, even want to use, but don’t know how to do, or don’t know where their own projects can be used, in line with let the developers to understand and to fit project, from giving up to the introduction, introduced this article.

Do I need to learn RxJava1.0 before learning RxJava2.0?

First of all, the core idea of RxJava1.0 and RxJava2.0 is the observer mode, but RxJava2.0 has optimized some methods based on RxJava1.0, which is convenient for developers to better understand its programming ideas. At the same time, it also adds some new methods to solve problems existing in 1.0, such as back pressure. So, great if you’ve studied RxJava1.0, you probably understand what observer mode is; If you haven’t learned RxJava1.0, don’t worry, because this article will start with the basic Observer mode and let you start with RxJava from a basic and simple point of view. To sum up, whether you have learned RxJava1.0 or not should not prevent you from learning this article.

Observer model

Before learning about RxJava2.0, we need to understand what observer mode is. As is my custom, I’ll start with an authoritative introduction from Baidu.com

A is the observed, B is the observer, B observes A, B does not need to keep an eye on A, but if A changes, B will actively inform B, B will make some changes accordingly. For example, suppose A is A serialized novel, and B is A reader. The reader subscribes to A serialized novel, and when A new serialized novel appears, it will be pushed to the reader. Readers don’t have to keep their eyes on the serials of novels, but new serials of novels will be actively pushed to readers. This is the observer model. RxJava was developed based on the Observer pattern.

Basic use of RxJava2.0

With an understanding of the observer pattern, let’s start learning about RxJava2.0. First, the rXJava 2.0-related class libraries are introduced.

The compile ‘IO. Reactivex. Rxjava2: rxjava: 2.0.1’

The compile ‘IO. Reactivex. Rxjava2: rxandroid: 2.0.1’

Proper use of posture:

Step 1: Create a serialized novel (Observed)

Observable novel= ObservableOnSubscribe (new ObservableOnSubscribe<String>() {@override public void subscribe(ObservableEmitter<String> emitter) throws Exception { emitter.onNext("Serial 1");
                emitter.onNext("Serial 2");
                emitter.onNext("Serial 3"); emitter.onComplete(); }});Copy the code

ObservableOnSubscribe, an Observable, generates an object using the create method. The parameter ObservableOnSubscribe is a schedule. The generic T is the type of object to operate on. The ObservableEmitter object in subscribe is an ObservableEmitter object. The ObservableEmitter object in subscribe is an ObservableEmitter object. ObservableEmitter (T value), void onError(Throwable error), void onComplete(), ObservableEmitter (T value), void onNext(Throwable error), Void onComplete() OnError and onComplete are mutually exclusive. The Observer can only receive one. OnComplete can be called repeatedly, but the Observer can only receive once. OnError cannot be called repeatedly. The second call will raise an exception.

Step 2: Create readers (Observers)

// Observer<String> reader=new Observer<String>() {@override public void onSubscribe(Disposable d) {mDisposable=d; Log.e(TAG,"onSubscribe");
            }
            @Override
            public void onNext(String value) {
                if ("2".equals(value)){
                    mDisposable.dispose();
                    return;
                }
                Log.e(TAG,"onNext:"+value);
            }
            @Override
            public void onError(Throwable e) {
                Log.e(TAG,"onError="+e.getMessage());
            }

            @Override
            public void onComplete() {
                Log.e(TAG,"onComplete()"); }};Copy the code

OnNext, onError, and onComplete correspond to the methods sent by the observer. This is equivalent to receiving. “OnSubscribe” (Disposable D) “Disposable”, “Disposable”, “Disposable”, “Disposable”, “Disposable”, “Disposable”, “Disposable”, “Disposable”, “Disposable”, “Disposable”, “Disposable”, “Disposable”, “Disposable”, “Disposable”, “Disposable”, “Disposable”, “Disposable”, “Disposable”, “Disposable” You can call McOmpounddisposable dispose() to cancel the subscription, and the serialized novel will no longer be pushed to readers when it is updated.

Step 3: Readers establish a subscription relationship with serial novels

novel.subscribe(reader); // One line of codeCopy the code

Observant here, you may have noticed how the novel subscribes to the reader, because RxJava mainly wants to keep its own chain programming, so it has to put Observable in front of it.

Let’s take a look at the output here

This is the simplest use of RxJava2.0, create a novel, create a reader, build a subscription, remember these three steps, you can implement a simple use of RxJava2.0.

Asynchronous and chained programming for RxJava2.0

As mentioned in the introduction, RxJava supports asynchrony, but how does RxJava do it?

This is where Scheduler is needed. Scheduler is a Scheduler used by RxJava to control threads.

When not set, RxJava follows the principle that the threads are consumed in the same thread as they are created, meaning that the threads do not change and remain the same.

Then we usually use RxJava are background, front desk call, in line with this principle, we need to call observeOn (AndroidSchedulers. MainThread ()), observeOn is the event callback thread, AndroidSchedulers. MainThread () a see will know that is the main thread, subscribeOn (Schedulers. IO ()), subscribeOn is the event thread of execution, Schedulers. IO is () the child thread, Schedulers.newthread () can also be used here, but IO threads can reuse idle threads, so IO () is more efficient than newThread() in most cases.

The previous code, based on asynchronous and chained programming principles, can be written as

Observable.create(new ObservableOnSubscribe<String>() {
            @Override
            public void subscribe(ObservableEmitter<String> emitter) throws Exception {
                emitter.onNext("Serial 1");
                emitter.onNext("Serial 2");
                emitter.onNext("Serial 3"); emitter.onComplete(); }}). ObserveOn (AndroidSchedulers mainThread ()) / / callback in the main thread. SubscribeOn (Schedulers. IO ()) / / execution in IO thread. The subscribe (new Observer<String>() { @Override public void onSubscribe(Disposable d) { Log.e(TAG,"onSubscribe");
                    }

                    @Override
                    public void onNext(String value) {
                        Log.e(TAG,"onNext:"+value);
                    }
                    @Override
                    public void onError(Throwable e) {
                        Log.e(TAG,"onError="+e.getMessage());
                    }
                    @Override
                    public void onComplete() {
                        Log.e(TAG,"onComplete()"); }});Copy the code

Now, this is the most common way to write RxJava, asynchronous + chained programming, and again, the subscribe method is overloaded. The subscribe () method is implemented with no arguments, which means that the reader doesn’t care what serialized novel comes out, and doesn’t read it. If the reader only cares about the contents of the onNext method, we can override subscribe(Consumer<? Spuer T> onNext) this method will reduce the code, although it is recommended to create an Observer for beginners.

Application scenarios

With all the usage of RxJava2.0, you have to ask under what circumstances? Here is a typical scenario.

1. In conjunction with Retrofit

Retrofit + RxJava online mode has been very fire, if you have don’t understand we can see the author of this article at https://www.jianshu.com/writer#/notebooks/5118090/notes/25405151

Use of Rxpermissions and other class libraries

The open source libraries based on RxJava, Rxpermissions, RxBinding, and RxBus have become common in many projects and have proven to be extremely useful.

3. Where asynchrony is used

Because RxJava is a support asynchronous chain programming, so all the use of asynchronous, we can use RxJava to complete, here are a few examples.

Scheduled Task Execution

 Observable.create(new ObservableOnSubscribe<Integer>() {
            @Override
            public void subscribe(ObservableEmitter<Integer> emitter) throws Exception {
                emitter.onNext(123);
                sleep(3000);
                emitter.onNext(456);
            }
        }).observeOn(AndroidSchedulers.mainThread())
                .subscribeOn(Schedulers.io())
                .subscribe(new Consumer<Integer>() {
                    @Override
                    public void accept(Integer integer) throws Exception {
                        Log.e(TAG,integer+"");
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {

                    }
                }, new Action() {
                    @Override
                    public void run() throws Exception {

                    }
                });
Copy the code

You’re probably thinking, with all this code, why not just go new Handler().postdelayed ().

If your process is simple with new Handler().postdelayed (), it doesn’t matter, but if your process is complicated, it’s time to see the benefits of RxJava. “As the process logic becomes more complex, RxJava can still keep it simple. **

For example, we need to load 10 pictures in sequence (loading pictures is a time-consuming process), of which the sixth one will be delayed by 3 seconds, the seventh one will be copied to sd card, and the eighth one will be uploaded to the network. So how do you do it? If Handler is used, it must be nested in various ways. The logic is so complicated it’s hard to look at it again.

But what about using RxJava?

Observable.create(new ObservableOnSubscribe<Drawable>() {
            @Override
            public void subscribe(ObservableEmitter<Drawable> emitter) throws Exception {
                for(int i=0; i<drawableRes.length; i++){ Drawable drawable=getResources().getDrawable(drawableRes[i]); // The sixth picture is delayed by 3 seconds after the shelfif(i==5){ sleep(3000); } // copy the 7th image to the SD cardif (i==6){
                        Bitmap bitmap=((BitmapDrawable)drawable).getBitmap();
                        saveBitmap(bitmap,"test.png", Bitmap.CompressFormat.PNG); } // Upload to the networkif(i==7){ updateIcon(drawable); } emitter.onNext(drawable); } } }).subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(new Consumer<Drawable>() { @override public void accept(Drawable Drawable) throws Exception {// Display it on the UI after callback}});Copy the code

There is no nesting and the logic is still concise, which is the benefit of RxJava.

summary

RxJava2.0 is a very useful asynchronous chained library that follows the observer pattern.

The observer model can be understood according to the relationship between serialized novels and readers. The observed is a serialized novel, and the observer is the reader. The reader subscribes to the novel.

The simplest steps to create RxJava are: 1) Create an observed object, 2) create an Observer object, and 3) create a subscription relationship.

RxJava2.0 application scenarios, as long as remember a word is that all asynchronous RxJava can be used to do it, especially complex scenes, the more complex scenes can reflect the benefits of RxJava.

As for RxJava, I will continue to publish two articles. One is “RxJava from Beginning to Advanced”, which covers some advanced operations of RxJava, such as transformations, common operators and back pressure. RxBinding, RxPerssions, etc.

About my Android learning path

Imperceptibly he has done a few years of development, by the time I remember just came out of the work to feel that they can cow force, now recall the feeling of good ignorance. The more you know, the less you know.

If your knowledge is a circle, the bigger your circle is, the bigger the circle touches the outside world.

In the process of my study, the first is to find a lot of information on the Internet, after all these data is the most rapid learning methods, we started here I put on my collected information on the Internet over the years, and then to my work experience to sum up, let you walk less detours, extract some Internet companies currently most mainstream Android development architecture technology, I hope I can help you!

Java language advanced and Android related technical kernel

Android applications are developed in Java and the SDK is written in Java. For Android, as long as the SDK is not rewritten by Kotlin, the Java language needs to be learned. And Android APK background server procedures are most likely to be built in the Java language, so master Java is also a kind of inevitable, this is why BAT interview why you die by the Java level.

APP development framework system

APP development is the most widely used knowledge nowadays, and most of them are CV engineers. The 2-8 rule in the programmer world: 80% of problems can be solved with only 20% of knowledge, and Android development is no exception. As a result, most of us have become code porters without realizing it. Code is easy to transport, architecture is difficult to copy, to become an architect, you must go to the project, read the source code, research principles.

Mobile architect project practice

Architect is not innate, is given in the project, so, we learn the technology needs to be combined with the project actual combat training, then the architecture of the most commonly used is not in the Android MVC and MVP, MVVM, but if these thoughts and modular, hierarchical, modular mixed together, then it’s not an easy thing, We need a truly battle-hardened architect to understand the implications of this.

Android Advanced Architecture technology; How to systematize learning?

A full set of systematic high-level architecture videos; Seven mainstream technology modules, video + source + notes

Design interviews and data Structure algorithms topics; Big factories will, to consolidate the foundation

The last

If you see this and you think it’s good, give it a thumbs up? If you think there is something worth improving, please leave a message. Will inquire seriously, correct inadequacy. thank you

Finally, for Android programmers, in addition to the above knowledge system, I have sorted out some information for you. The content shared includes but not limited to advanced UI, performance optimization, mobile architect, NDK, Hybrid development (ReactNative+Weex) wechat applet, Flutter and other advanced Android practice technologies; Hope to help you, but also save you in the online information search time to learn, can also share dynamic friends around to learn together!

The reason why someone is always better than you is because they are already better and are constantly trying to become better, while you are still satisfied with the status quo and secretly happy! I hope you can give me a thumbs-up and follow me, and I will update the technical dry goods in the future. Thank you for your support!

Forwarding sharing + attention, private reply [information] to get more knowledge

The road to being an Android architect is a long one.