Android project: Use Jetpack components to build a MVVM-based RxAndroid (RxJava), Retrofit, OkHttp project

Through the learning of RxAndroid, Retrofit and OkHttp, use them to integrate and build a project based on MVVM.
Using Android Jetpack components Databinding, ViewModel, LiveData, Lifecycle
through this blog, you can learn how to use these frameworks to integrate and build a project.

Github address of the source code used in this blog: MVVM Demo

Now let’s get to the main topic. This article takes the public account list data display as an example. The article catalog follows the Demo project from data to business logic processing and finally to interface display.

Ready to work

  • Add dependency
    The version of the dependency must match, otherwise there will be some messy problems. For details, please refer to my previous blog integration error

    Because the new features of JDK8 are used in Retrofit2, in addition to dependencies, support must be added.

	// Support new features of JDK1.8
    compileOptions {
    
    
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }

	// Android JetPack,也可以分别添加使用具体的某个组件的依赖
    implementation 'androidx.lifecycle:lifecycle-extensions:2.2.0'

	// okHttp 3.14
    implementation 'com.squareup.okhttp3:okhttp:3.14.9'
    // Retrofit 2.9
    implementation 'com.squareup.retrofit2:retrofit:2.9.0'
    // Convert Google Json(Convert the result to Model)
    implementation 'com.squareup.retrofit2:converter-gson:2.3.0'
    // Retrofit CallAdapter convert to RxJava
    implementation 'com.squareup.retrofit2:adapter-rxjava3:2.9.0'
    // RxAndroid 3.0
    implementation 'io.reactivex.rxjava3:rxandroid:3.0.0'
  • Declare permissions
    <uses-permission android:name="android.permission.INTERNET" />
  • Project directory
    Project directory

    After creating the catalog, you can start work.

Request data

This example uses Android as the data source.

We use OkHttp to implement network requests, Retrofit calls back in the form of interfaces, and better handles business and display work through RxAndroid.

  1. Create interface
    First, create the interface MpService.java for the official account list data, and then declare this geListData()
	@GET("wxarticle/chapters/json")
    Observable<BaseData<List<MpBean>>> getListData();









    // 也可以使用GET或者POST来请求
    /**
     * Request Buyer Data for GET
     * @param id dateId
     * @return buyer data
     */
    @GET("buyer/date/get")
    Observable<BaseData<Map<String, Map<String, String>>>> getBuyerData(@Query("dateId") String id);

    /**
     * Request Buyer Data for POST
     * @param dateId dateId
     * @return buyer data
     */
    @FormUrlEncoded
    @POST("buyer/date/get")
    Observable<BaseData<Map<String, Map<String, String>>>> postBuyerData(@Field("dateId") String dateId);
  1. Proxy object
    With the interface, it cannot be used directly. We need to obtain the proxy object and pass the interface in MainModel.java through the create method of Retrofit. Of course, we have to create a Retrofit object first
	private Retrofit retrofit = new Retrofit.Builder().
            baseUrl(HttpConfig.BASE_URL)
            .addConverterFactory(GsonConverterFactory.create())
            .addCallAdapterFactory(RxJava3CallAdapterFactory.create())
            .build();
    // 获取代理对象
	retrofit.create(MpSerivce.class)
  1. Establishing a subscription
    Our interface returns an Observable, so we need to pass in an Observer and then establish a subscription relationship.
    Among them, getListData is used to obtain Observable, subscribe to establish a subscription relationship, and specify a working thread.
	/**
     * get the proxy object of MpService
     * get the observable of proxy object
     * build a subscription relationship
     * @param observer observer
     */
    public void subscribe(Observer<BaseData<List<MpBean>>> observer) {
    
    
        retrofit.create(MpSerivce.class).getListData()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(observer);
    }

Processing logic

Create ViewModel, Adapter and Adapter layout files.

  1. Create Observer to respond to events
		Observer<BaseData<List<MpBean>>> observer = new Observer<BaseData<List<MpBean>>>() {
    
    
            @Override
            public void onSubscribe(@io.reactivex.rxjava3.annotations.NonNull Disposable d) {
    
    

            }

            @Override
            public void onNext(@io.reactivex.rxjava3.annotations.NonNull BaseData<List<MpBean>> listBaseData) {
    
    
				if (listBaseData.getErrorCode() == 0) {
    
    
                    mainAdapter.setList(listBaseData.getData());
                }
            }

            @Override
            public void onError(@io.reactivex.rxjava3.annotations.NonNull Throwable e) {
    
    
                // error
            }

            @Override
            public void onComplete() {
    
    
                Toast.makeText(mContext, "get data completed.", Toast.LENGTH_SHORT).show();
            }
        };
        // build subscription relationship
        mainModel.subscribe(observer);
  1. Create Adapter processing
	@NonNull
    @Override
    public MainAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
    
    
        AdapterMainBinding adapterMainBinding = DataBindingUtil.inflate(inflater, R.layout.adapter_main, parent, false);
        return new ViewHolder(adapterMainBinding);
    }

    @Override
    public void onBindViewHolder(@NonNull MainAdapter.ViewHolder holder, int position) {
    
    
        // 不再需要单独对控件赋值,通过DataBinding数据绑定
        MpBean bean = list.get(position);
        if (bean != null) {
    
    
            holder.binding.setMp(bean);
        }
    }

    class ViewHolder extends RecyclerView.ViewHolder {
    
    
        private AdapterMainBinding binding;
        // 不需要使用itemView进行findViewById,而是直接使用DataBinding
        ViewHolder(@NonNull AdapterMainBinding binding) {
    
    
            super(binding.getRoot());
            this.binding = binding;
        }
    }

Interface display

It can be called through the View Model in MainActivity.

	@Override
    protected void onCreate(Bundle savedInstanceState) {
    
    
        super.onCreate(savedInstanceState);
        mainBinding = DataBindingUtil.setContentView(this, R.layout.activity_main);
        mainViewModel = new ViewModelProvider(this).get(MainViewModel.class);
        mainViewModel.getMpData();
        mainBinding.rvMain.setAdapter(mainViewModel.mainAdapter);
    }

Show results

Interface effect

supplement

If you want to use LiveData and Lifecycle, we can follow the following three steps.

  1. Create LiveData
    Obviously, we need to create LiveData in ViewModel
	public class NameViewModel extends ViewModel {
    
    

    // Create a LiveData with a String
    private MutableLiveData<String> currentName;

        public MutableLiveData<String> getCurrentName() {
    
    
            if (currentName == null) {
    
    
                currentName = new MutableLiveData<String>();
            }
            return currentName;
        }

    // Rest of the ViewModel...
    }
  1. Observe LiveData
    by creating an observer to observe the changes in LiveData
	public class NameActivity extends AppCompatActivity {
    
    

        private NameViewModel model;

        @Override
        protected void onCreate(Bundle savedInstanceState) {
    
    
            super.onCreate(savedInstanceState);

            // Other code to setup the activity...

            // Get the ViewModel.
            model = new ViewModelProvider(this).get(NameViewModel.class);

			// 下面是核心代码
            // Create the observer which updates the UI.
            final Observer<String> nameObserver = new Observer<String>() {
    
    
                @Override
                public void onChanged(@Nullable final String newName) {
    
    
                    // Update the UI, in this case, a TextView.
                    nameTextView.setText(newName);
                }
            };

            // Observe the LiveData, passing in this activity as the LifecycleOwner and the observer.
            model.getCurrentName().observe(this, nameObserver);
        }
    }
  1. Update LiveData
    and then we can update LiveData. There are two methods: setValue and postValue. The difference is that setValue is used in the main thread, while postValue is updated in the worker thread.
	button.setOnClickListener(new OnClickListener() {
    
    
        @Override
        public void onClick(View v) {
    
    
            String anotherName = "John Doe";
            // 下面的代码用来更新LiveData
            model.getCurrentName().setValue(anotherName);
        }
    });

The above is about the use of LiveData and Lifecycle. In fact, there are more detailed official documentation on the Android developer platform. You can study it in depth.

End

This blog basically ends here. If there is an error or something you don't understand, you can leave a message or view the code used in this article.
Github address: If MVVM Demo
feels helpful to you, please feel free to Star, thank you.

This article refers to the blog as follows:
Retrofit + RxAndroid common bugs
for Android developers RxJava detailed explanation,
do you really use Retrofit?
Android MVVM build project basic version
Android developer official

Guess you like

Origin blog.csdn.net/A_Intelligence/article/details/109518823