Introduction to Rx thinking

What is reactive programming

The official explanation is: In the computer field, reactive programming is an asynchronous programming paradigm that focuses on data flow and change delivery.
Do you think you don’t understand it? In fact, I don’t understand it either, but after reading many blogs, I understand that: the starting point and end point of a task are continuous, there is no break in the middle, but interception or processing can be done in the middle.
For example:
I am thirsty (starting point), and then I am going to drink water (end point).
Starting point (distribution event (Path): thirsty) --> go to the restaurant --> open the refrigerator --> take out the drink --> end point (drink consumption event)
analysis: we go to the restaurant because we are thirsty, so I just go, so going to the restaurant is based on being thirsty. When you arrive at the restaurant, you open the refrigerator. You can only open the refrigerator because you have arrived at the restaurant. Therefore, you need to open the refrigerator on the basis of arriving at the restaurant. Dispensing drinks should be carried out on the basis of opening the refrigerator, and then drink it up in one gulp, the event will be consumed, that is, the execution of this task is completed. There is no break in the middle, and each operation is carried out on the basis of the end of the previous operation. This is Rx thinking

Examples of Rx thinking

        //TODO 第二步:需求:将String类型转换为Bitmap类型
        Observable.just("https://img-blog.csdnimg.cn/20190626094453625.jpg")
                //TODO 第三步:将String转换成Bitmap类型并传给下一层
                .map(new Function<String, Bitmap>() {
    
    
                    @Override
                    public Bitmap apply(String s) throws Exception {
    
    
                        try {
    
    
                            URL url = new URL(s);
                            HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
                            urlConnection.setRequestMethod("GET");
                            urlConnection.setConnectTimeout(3000);
                            int responseCode = urlConnection.getResponseCode();
                            if (responseCode == HttpURLConnection.HTTP_OK) {
    
    
                                InputStream inputStream = urlConnection.getInputStream();
                                return BitmapFactory.decodeStream(inputStream);
                            }
                        } catch (Exception e) {
    
    
                            e.printStackTrace();
                        }
                        return null;
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())//主线程
                .subscribeOn(Schedulers.io())//子线程
                //TODO 导火索,上面的算是检查逻辑,直到这里才开始执行
                .subscribe(new Observer<Bitmap>() {
    
    
                    @Override//TODO 第一步(点击完下载按钮,先执行此方法也就是先弹出加载框)
                    public void onSubscribe(Disposable d) {
    
    
                        progressDialog = new ProgressDialog(MainActivity.this);
                        progressDialog.setTitle("正在加载中");
                        //显示加载框
                        progressDialog.show();
                    }

                    @Override//TODO 第四步:成功
                    public void onNext(Bitmap s) {
    
    
                        imageView.setImageBitmap(s);
                    }

                    @Override//TODO 链条思维发生了异常
                    public void onError(Throwable e) {
    
    
                       
                    }

                    @Override//TODO 第五步:整个链条思维全部结束
                    public void onComplete() {
    
    
                    	//隐藏加载框
                        if (progressDialog != null) {
    
    
                            progressDialog.dismiss();
                        }
                    }
                });

We need to download a picture (starting point) from the Internet, and then display it on the picture control (end point)

    //起点
        Observable.just("https://img-blog.csdnimg.cn/20190626094453625.jpg")
                //终点
                .subscribe(new Observer<String>() {
    
    
                    @Override
                    public void onSubscribe(Disposable d) {
    
    
                        
                    }

                    @Override
                    public void onNext(String s) {
    
    
                        
                    }

                    @Override
                    public void onError(Throwable e) {
    
    

                    }

                    @Override
                    public void onComplete() {
    
    

                    }
                });

The Path at our starting point is of String type, so the generic type of the ending point is also of Sting type, because the ending point is based on the execution result of the starting point, but our structure needs Bitmap type, so we need to perform type conversion

    	//起点
        Observable.just("https://img-blog.csdnimg.cn/20190626094453625.jpg")
                //类型转换Sting——>Bitmap
                .map(new Function<String, Bitmap>() {
    
    
                    @Override
                    public Bitmap apply(String s) throws Exception {
    
    
                        //进行网络请求
                        try {
    
    
                            URL url = new URL(s);
                            HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
                            urlConnection.setRequestMethod("GET");
                            urlConnection.setConnectTimeout(3000);
                            int responseCode = urlConnection.getResponseCode();
                            if (responseCode == HttpURLConnection.HTTP_OK) {
    
    
                                InputStream inputStream = urlConnection.getInputStream();
                                Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
                                inputStream.close();
                                return bitmap;
                            }
                        } catch (Exception e) {
    
    
                            e.printStackTrace();
                        }
                        return null;
                    }
                })
                //终点
                .subscribe(new Observer<Bitmap>() {
    
    
                    @Override
                    public void onSubscribe(Disposable d) {
    
    

                    }

                    @Override
                    public void onNext(Bitmap s) {
    
    

                    }

                    @Override
                    public void onError(Throwable e) {
    
    

                    }

                    @Override
                    public void onComplete() {
    
    

                    }
                });

And because our network requests are performed in sub-threads, and UI updates are performed in the main thread, so we need to switch threads

 //起点
        Observable.just("https://img-blog.csdnimg.cn/20190626094453625.jpg")
                //TODO 类型转换Sting——>Bitmap
                .map(new Function<String, Bitmap>() {
    
    
                    @Override
                    public Bitmap apply(String s) throws Exception {
    
    
                        //进行网络请求
                        try {
    
    
                            URL url = new URL(s);
                            HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
                            urlConnection.setRequestMethod("GET");
                            urlConnection.setConnectTimeout(3000);
                            int responseCode = urlConnection.getResponseCode();
                            if (responseCode == HttpURLConnection.HTTP_OK) {
    
    
                                InputStream inputStream = urlConnection.getInputStream();
                                return BitmapFactory.decodeStream(inputStream);
                            }
                        } catch (Exception e) {
    
    
                            e.printStackTrace();
                        }
                        return null;
                    }
                })
                //TODO 线程切换
                .observeOn(AndroidSchedulers.mainThread())//主线程
                .subscribeOn(Schedulers.io())//子线程
                //终点
                .subscribe(new Observer<Bitmap>() {
    
    
                    @Override
                    public void onSubscribe(Disposable d) {
    
    

                    }

                    @Override
                    public void onNext(Bitmap s) {
    
    

                    }

                    @Override
                    public void onError(Throwable e) {
    
    

                    }

                    @Override
                    public void onComplete() {
    
    

                    }
                });

Then get the response value and set it on the picture control. At this time, you will find that there is no loaded bullet box. To achieve this effect, we need to define a ProgressDialog first, and then initialize it in the onSubscribe() method at the end And display, and remember to hide the bullet box after the chain thinking is over.

 .subscribe(new Observer<Bitmap>() {
    
    
                    @Override//TODO 第一步(点击完下载按钮,先执行此方法也就是先弹出加载框)
                    public void onSubscribe(Disposable d) {
    
    
                        progressDialog = new ProgressDialog(MainActivity.this);
                        progressDialog.setTitle("正在加载中");
                        //显示加载框
                        progressDialog.show();
                    }

                    @Override//TODO 第四步:成功
                    public void onNext(Bitmap s) {
    
    
                    	//设置图片
                        imageView.setImageBitmap(s);
                    }

                    @Override//TODO 链条思维发生了异常
                    public void onError(Throwable e) {
    
    
                       
                    }

                    @Override//TODO 第五步:整个链条思维全部结束
                    public void onComplete() {
    
    
                        if (progressDialog != null) {
    
    
                            progressDialog.dismiss();
                        }
                    }

The above is the Rx thinking that the author understands, and I share it with you in the hope that it will be helpful to you.

Supongo que te gusta

Origin blog.csdn.net/m0_46366678/article/details/123796663
Recomendado
Clasificación