Use of RxJava for Android development

RxJava is responsive programming, which can also be understood as streaming programming, and the core is the observer mode.

Rx is a reactive extension of Microsoft.Net. Rx provides an easy way to create asynchronous, event-driven programs with observable sequences. In 2012, Netflix began to migrate .NET Rx to the JVM in response to growing business needs. And in February 2013, RxJava was officially shown to the outside world.

Using RxJava can make programming more concise and understandable, and avoid callback hell.

Operator Description

Reference RxJava operator summary

1. Create operator: create Observable object & send event

2. Conversion operator: Transform the event sent by the Observable. Transform the data sent by Observable according to certain rules, and then emit the transformed data. Transformation operators include map, flatMap, concatMap, switchMap, buffer, groupBy, etc.

3. Merge operator: combine multiple observables (Observable) & merge the events that need to be sent. Contains: concatMap(), concat(), merge(), mergeArray(), concateArray(), reduce(), collect(), startWith(), zip(), count(), etc.

4. Functional operator: assists the Observable to implement some functional requirements when sending events, such as error handling and thread scheduling.

5. Filter operator: used to filter and select the data sent by Observable. Let Observable return the data we need. Filter operators are buffer(), filter(), skip(), take(), skipLast(), takeLast(), throttleFirst(), and distractUntilChange().

Modify the configuration and add dependent packages

implementation "io.reactivex.rxjava3:rxjava:3.1.5"
implementation 'io.reactivex.rxjava3:rxandroid:3.0.2'

The following example demonstrates downloading pictures from the network and displaying them on the page, so you need to add OkHttp dependencies and increase network permissions

implementation "com.squareup.okhttp3:okhttp:4.10.0"

Modify AndroidManifest.xml to increase network permissions

<uses-permission android:name="android.permission.INTERNET"/>

Code example, the network picture below

The layout is relatively simple, just a button, an imageView

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="点我加载图片"
        android:onClick="loadImage"
        />
    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/imageview"
        />
</LinearLayout>

2) Modify the Activity class

The execution sequence is as follows:
1. Display the picture loading box
2. Start point, send data
3. Execute the download picture operation
4. Display the picture
5. End and hide the loading box

public class MainActivity extends AppCompatActivity {
    
    

    ActivityMainBinding binding;
    private ProgressDialog pg;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
    
    
        super.onCreate(savedInstanceState);
        binding = ActivityMainBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
    }

    public void loadImage(View view) {
    
    
        OkHttpClient okHttpClient = new OkHttpClient();
        String path = "https://www.dasouji.com/wp-content/uploads/2020/12/@ukwanghyun.jpg";
        // 2、起点,发送数据
        Observable.just(path)
                // 3、执行下载图片操作
                .map(new Function<String, Bitmap>() {
    
    
                    @Override
                    public Bitmap apply(String url) throws Throwable {
    
    
                        Request request = new Request.Builder().url(url).build();
                        Response response = okHttpClient.newCall(request).execute();
                        if (response.isSuccessful()) {
    
    
                            Bitmap bitmap = BitmapFactory.decodeStream(response.body().byteStream());
                            return bitmap;
                        }
                        return null;
                    }
                })
                // 给上面的操作分配异步线程
                .subscribeOn(Schedulers.io())

                // 给终点分配安卓主线程
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<Bitmap>() {
    
    
                    // 1、显示图片加载框
                    @Override
                    public void onSubscribe(@NonNull Disposable d) {
    
    
                        pg = new ProgressDialog(MainActivity.this);
                        pg.setTitle("图片加载中...");
                        pg.show();

                    }

                    // 4、显示图片
                    @Override
                    public void onNext(@NonNull Bitmap bitmap) {
    
    
                        binding.imageview.setImageBitmap(bitmap);
                    }

                    @Override
                    public void onError(@NonNull Throwable e) {
    
    

                    }

                    // 5、结束,隐藏加载框
                    @Override
                    public void onComplete() {
    
    
                        if (pg != null) {
    
    
                            pg.dismiss();
                        }
                    }
                });
    }
}

reference

  • Summary of RxJava operators https://blog.csdn.net/chuyouyinghe/article/details/122806097
  • https://github.com/ReactiveX/RxAndroid
  • https://github.com/ReactiveX/RxJava

Guess you like

Origin blog.csdn.net/wlddhj/article/details/127802534