preface

  • This series is based on Carson_Ho’s bookRxJava series tutorials”Series of articles, the relevant knowledge points of RxJava comb, the pictures are all from” RxJava series tutorial “. These articles are of great help to me. I always appreciate the way in which the relevant knowledge points are combined with examples in life. In particular, the principles of RxJava are adoptedCustomers go to restaurants to eatI was impressed by this life example. Because many conceptual things are too abstract when we learn them, we use association method to combine them with examples in life, which makes it more interesting and undoubtedly reduces the difficulty of understanding and facilitates our learning. For me, one of my personal lessons about learning something new is that the order of thinking goes like this:
    • What is RxJava?
    • What is RxJava for? What is the function? Is there anything that has the same kinetic energy?
    • What are the advantages of RxJava? Why do you have to use it?
    • How is RxJava used?
    • What does RxJava work on?
    • .

define

  • A library that uses observable sequences to compose asynchronous, event-based programs on the Java VM.

role

  • Asynchronous operation, similar to the Android AsyncTask, Handler function.

The characteristics of

  • Chain calls based on event flows can keep code logic concise even when the program logic is extremely complex.

The principle of

  • The asynchronous implementation of RxJava is implemented through an extended observer pattern. Observables send events sequentially to observers by subscribing. The observers receive events sequentially and respond accordingly.

    • Observable
      • Function: Determines when and what events are triggered.
      • Create method:
        • Observable.just(T…) The parameter is single.
        • Observable. From (T[])/Observable. FromArray (Iterable
          ) takes an array or an Itera
    • Observer (Observice)
      • Action: What will happen when the event is triggered.
      • The implementation class has Observer/Subscriber
  • For example, a customer goes to a restaurant to eat, as shown in the picture below

The basic use

  • Using the step

  • The event type

  • The sample code

public class MainActivity extends AppCompatActivity {

    private static final String TAG = "RxJava";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main); Create (new ObservableOnSubscribe<Integer>() {// 1. @override Public void subscribe(ObservableEmitter<Integer> Emitter) throws Exception {emitter. OnNext (1); emitter.onNext(2); emitter.onNext(3); emitter.onComplete(); Emitter. OnNext (4); Emitter. OnNext (4); emitter.onNext(5); } }).subscribe(new Observer<Integer>() { //2. Connect the observer to the observed by subscribing. Override public void onSubscribe(Disposable d) {Log."Start using subscribe connections.");
            }

            @Override
            public void onNext(Integer value) {
                Log.d(TAG, "To the Next event" + value + "Respond");
            }

            @Override
            public void onError(Throwable e) {
                Log.d(TAG, "Respond to an Error event");
            }
            @Override
            public void onComplete() {
                Log.d(TAG, "Respond to the Complete Event"); }}); Subscribe () > subscribe () > watcher.onNext () > watcher.oncomplete ()}}Copy the code
  • Running effect

  • case

    • Retrieves the image from the specified drawable file ID, displays it in the ImageView, and prints a Toast error if an exception occurs.

    private void showImageDemo() {
        final int drawID = R.mipmap.ic_launcher;
        Observable
                .create(new ObservableOnSubscribe<Drawable>() {
                    @Override
                    public void subscribe(ObservableEmitter<Drawable> emitter) throws Exception {
                        Drawable drawable = ContextCompat.getDrawable(MainActivity.this, drawID);
                        emitter.onNext(drawable);
                        emitter.onComplete();

                    }
                })
                .subscribe(new Observer<Drawable>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(Drawable drawable) {
                        imageView.setImageDrawable(drawable);
                    }

                    @Override
                    public void onError(Throwable e) {
                        Toast.makeText(MainActivity.this, "Error", Toast.LENGTH_SHORT).show();
                    }
                    @Override
                    public void onComplete() {}}); }Copy the code
  • Additional instructions
    • Observer subscribe() has multiple overloaded methods.

    • Disposable dispose() can be used to cut off the connection between the observer and the observed. That is, the observer cannot continue to receive events from the observed, but the observed can continue to send events.

}).subscribe(new Observer<Integer>() { // 1. Private Disposable mDisposable; @Override public void onSubscribe(Disposable d) { Log.d(TAG,"Start using subscribe connections."); // 2. Assign mDisposable = d to Disposable; } @Override public void onNext(Integer value) { Log.d(TAG,"To the Next event" + value + "Respond");
                if(value == 2) {// 3. Set to disconnect observer from observed upon receipt of the second event. mDisposable.dispose(); Log.d(TAG,"The connection has been severed." + mDisposable.isDisposed());
                }
            }

            @Override
            public void onError(Throwable e) {
                Log.d(TAG, "Respond to an Error event");
            }

            @Override
            public void onComplete() {
                Log.d(TAG, "Respond to the Complete Event"); }});Copy the code
  • Running effect