Preface:
The classmate of everyone, there was a time not to update the article, also recently in learning HongMeng development support, just thinking about the android part moved to HongMeng use knowledge Because the basic language is Java language (android Java and kotlin) so I wrote this tutorial now So please donate said we begin # # 2
The preparatory work
Installation of the Hongmeng development environment you can see my previous article
The tripartite library you need to use
/ / okhttp3 implementation 'com. Squareup. Okhttp3: okhttp: 4.2.0' implementation "Com. Squareup. Okhttp3: logging - interceptor: 3.10.0" / / retrofit2 implementation 'com. Squareup. Retrofit2: retrofit: 2.9.0' Implementation 'com. Squareup. Retrofit2: converter - gson: 2.9.0' implementation 'com. Squareup. Retrofit2: adapter - rxjava3:2.9.0'Copy the code
Please add dependencies in build.gradle and sygn Now download dependencies to implement MainAbility layout code
<? The XML version = "1.0" encoding = "utf-8"? > <DirectionalLayout xmlns:ohos="http://schemas.huawei.com/res/ohos" ohos:height="match_parent" ohos:width="match_parent" ohos:orientation="vertical"> <Text ohos:id="$+id:text_fruit_tag" ohos:height="35vp" Ohos :width="match_parent" OHOs: background_Element ="$graphic:text_element" OHOs :layout_alignment="left" oHOs :text=" account" ohos:text_size="85" ohos:right_margin="20vp" ohos:left_margin="20vp" ohos:top_margin="25vp" ohos:text_color="#000000" /> <TextField ohos:id="$+id:text_username" ohos:height="35vp" ohos:width="match_parent" ohos:background_element="$graphic:text_element" ohos:layout_alignment="left" ohos:text_size="50" ohos:right_margin="20vp" ohos:left_margin="20vp" ohos:text_color="#000000" ohos:top_margin="25vp" Ohos :basement="#000099" ohos:hint=" "/> <Text ohos:id="$+id:text_number_tag" ohos:height="35vp" Ohos :width="match_parent" oHOs: background_Element ="$graphic:text_element" OHOs :layout_alignment="left" oHOs :text=" password" ohos:text_size="85" ohos:right_margin="20vp" ohos:left_margin="20vp" ohos:text_color="#000000" ohos:top_margin="25vp" /> <TextField ohos:id="$+id:text_password" ohos:height="35vp" ohos:width="match_parent" ohos:background_element="$graphic:text_element" ohos:layout_alignment="left" ohos:text_size="50" ohos:right_margin="20vp" ohos:left_margin="20vp" ohos:text_color="#000000" ohos:top_margin="25vp" <Button ohos:id="$+id:login_btn" ohos:width="match_parent" Ohos :height="50vp" oHOs :text=" $graphic:button_element" oHOs :text_size="50" ohos:text_color="#FFFFFF" ohos:top_margin="25vp" ohos:right_margin="20vp" ohos:left_margin="20vp" /> </DirectionalLayout>Copy the code
The layout effect
Our goal is very clear we want to take the contents of the two input fields and then call the network interface to do the login operation which is very simple but today we are going to do it using MVP+ Rxjava+Retrofit+ OKHTTP
Network core
RetrofitClient classes encapsulate
package com.example.hmsrxjava_demo.net; import java.io.IOException; import io.reactivex.rxjava3.annotations.NonNull; import ohos.agp.render.render3d.BuildConfig; import okhttp3.Interceptor; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.Response; import okhttp3.logging.HttpLoggingInterceptor; import retrofit2.Retrofit; import retrofit2.adapter.rxjava3.RxJava3CallAdapterFactory; import retrofit2.converter.gson.GsonConverterFactory; Public class RetrofitClient {private static volatile RetrofitClient instance; private APIService apiService; private String baseUrl = "https://www.wanandroid.com"; private Retrofit retrofit; private OkHttpClient okHttpClient; private RetrofitClient() { } public static RetrofitClient getInstance() { if (instance == null) { synchronized (RetrofitClient.class) { if (instance == null) { instance = new RetrofitClient(); } } } return instance; Header ** @return */ private Interceptor getHeaderInterceptor() {return new Interceptor() {@override public Response intercept(@NonNull Chain chain) throws IOException { Request original = chain.request(); Request.Builder requestBuilder = original.newBuilder(); // Request.Builder requestBuilder = original.newBuilder().header(" Token ", ""); Request request = requestBuilder.build(); return chain.proceed(request); }}; } /** * private Interceptor getInterceptor() {HttpLoggingInterceptor Interceptor = new HttpLoggingInterceptor(); / / show log interceptor. SetLevel (HttpLoggingInterceptor. Level. BODY); return interceptor; } public OkHttpClient getOkHttpClient() {if (OkHttpClient == null) {// If (buildconfig.debug) { OkHttpClient = new okHttpClient ().newBuilder() // Set header.addInterceptor (getHeaderInterceptor()) // Set interceptor .addInterceptor(getInterceptor()) .build(); } else {okHttpClient = new okHttpClient ().newBuilder() // Set header.addInterceptor (getHeaderInterceptor()).build(); } } return okHttpClient; } public APIService getApi() {// Initialize a client, otherwise RetroFit will add a default if (retroFIT == null) {retroFIT = new Retrofit. Builder () the requested Url / / set the network address. The baseUrl (baseUrl) / / set data parser. AddConverterFactory (GsonConverterFactory. The create ()) // Set up the network request adapter, To support RxJava and RxAndroid. AddCallAdapterFactory (RxJava3CallAdapterFactory. The create ()). The client (getOkHttpClient ()). The build (); If (apiService==null){apiService= retrofit.create(apiService. Class); } return apiService; }}Copy the code
We wrote a singleton to get the RetrofitClient power and set up the request header handler and set up the OKHTTP log interceptor and then defined the getApi method to get the APIService instance
-
RxScheduler
RXjava thread scheduling
package com.example.hmsrxjava_demo.net; import com.example.hmsrxjava_demo.HarmonySchedulers; import org.reactivestreams.Publisher; import io.reactivex.rxjava3.core.Flowable; import io.reactivex.rxjava3.core.FlowableTransformer; import io.reactivex.rxjava3.core.Observable; import io.reactivex.rxjava3.core.ObservableSource; import io.reactivex.rxjava3.core.ObservableTransformer; import io.reactivex.rxjava3.schedulers.Schedulers; / * * * the description: RXjava thread scheduling */ public class RxScheduler {/** ** unified thread handling ** @param <T> specifies the generic type * @return FlowableTransformer */ public static <T> FlowableTransformer< T, T> Flo_io_main() { return new FlowableTransformer<T, T>() { @Override public Publisher<T> apply(Flowable<T> upstream) { return upstream.subscribeOn(Schedulers.io()) .observeOn(HarmonySchedulers.mainThread()); }}; } public static <T> ObservableTransformer<T, T> Obs_io_main() { return new ObservableTransformer<T, T>() { @Override public ObservableSource<T> apply( Observable<T> upstream) { return upstream.subscribeOn(Schedulers.io()) .observeOn(HarmonySchedulers.mainThread()); }}; }}Copy the code
This code is a reference of the android part there is HarmonySchedulers. MainThread () refer to the android inside oneself achieved
-
APIService
The interface class that handles network requests and all network requests are written in APIService similar to Android Retrofitle
package com.example.hmsrxjava_demo.net; import com.example.hmsrxjava_demo.bean.BaseObjectBean; import com.example.hmsrxjava_demo.bean.LoginBean; import io.reactivex.rxjava3.core.Observable; import retrofit2.http.Field; import retrofit2.http.FormUrlEncoded; import retrofit2.http.POST; / * * * the Description: */ public interface APIService {/** * coded ** @param username * @param password * @return */ @formurlencoded @POST("user/login") Observable<BaseObjectBean<LoginBean>> login(@Field("username") String username, @Field("password") String password); }Copy the code
The base class
-
BaseAbility
package com.example.hmsrxjava_demo.base; import ohos.aafwk.ability.Ability; import ohos.aafwk.content.Intent; public abstract class BaseAbility extends Ability { @Override protected void onStart(Intent intent) { super.onStart(intent); super.setUIContent(getLayoutId()); initView(); } @Override protected void onStop() { super.onStop(); } /** * set layout ** @return */ public abstract int getLayoutId(); Public void initView(); }Copy the code
-
BaseMvpAbility
package com.example.hmsrxjava_demo.base;
import ohos.aafwk.content.Intent;
public abstract class BaseMvpAbility <T extends BasePresenter>extends BaseAbility implements BaseView {
protected T mPresenter;
@Override
protected void onStart(Intent intent) {
super.onStart(intent);
}
@Override
protected void onStop() {
if (mPresenter != null) {
mPresenter.detachView();
}
super.onStop();
}
}
Copy the code
-
BasePresenter
package com.example.hmsrxjava_demo.base; Public class BasePresenter<V extends BaseView> {protected V mView; Public void attachView(V view) {this.mview = view; } /** * Public void detachView() {this.mView = null; } public Boolean isViewAttached() {return mached! = null; }}Copy the code
-
BaseView
package com.example.hmsrxjava_demo.base; /** * Description: */ public interface BaseView {/** * public interface BaseView {/** * /** * hidden load */ void hideLoading(); /** * @param errMessage */ void onError(String errMessage); }Copy the code
Model layer
package com.example.hmsrxjava_demo.contract; import com.example.hmsrxjava_demo.base.BaseView; import com.example.hmsrxjava_demo.bean.BaseObjectBean; import com.example.hmsrxjava_demo.bean.LoginBean; import io.reactivex.rxjava3.core.Observable; / * * * the Description: */ public interface MainContract { interface Model { Observable<BaseObjectBean<LoginBean>> login(String username, String password); } interface View extends BaseView { @Override void showLoading(); @Override void hideLoading(); @Override void onError(String errMessage); void onSuccess(BaseObjectBean<LoginBean> bean); } interface Presenter {/** * login ** @param username * @param password */ void login(String username, String password); }}Copy the code
# # model implementation layer
package com.example.hmsrxjava_demo.model; import com.example.hmsrxjava_demo.bean.BaseObjectBean; import com.example.hmsrxjava_demo.bean.LoginBean; import com.example.hmsrxjava_demo.contract.MainContract; import com.example.hmsrxjava_demo.net.RetrofitClient; import io.reactivex.rxjava3.core.Observable; / * * * the Description: */ public class MainModel implements MainContract.Model { private static final String TAG = "MainModel"; @Override public Observable<BaseObjectBean<LoginBean>> login(String username, String password) {system.out.println ("MainModel login is called "); return RetrofitClient.getInstance().getApi().login(username,password); }}Copy the code
Presenter layer
package com.example.hmsrxjava_demo.presenter; import com.example.hmsrxjava_demo.base.BasePresenter; import com.example.hmsrxjava_demo.bean.BaseObjectBean; import com.example.hmsrxjava_demo.bean.LoginBean; import com.example.hmsrxjava_demo.contract.MainContract; import com.example.hmsrxjava_demo.model.MainModel; import com.example.hmsrxjava_demo.net.RxScheduler; import io.reactivex.rxjava3.annotations.NonNull; import io.reactivex.rxjava3.core.Observer; import io.reactivex.rxjava3.disposables.Disposable; / * * * the Description: */ public class MainPresenter extends BasePresenter<MainContract.View> implements MainContract.Presenter { private MainContract.Model model; public MainPresenter() { model = new MainModel(); } @override public void login(String username, String password) {if (! isViewAttached()) { return; } model.login(username, password) .compose(RxScheduler.Obs_io_main()) .subscribe(new Observer<BaseObjectBean<LoginBean>>() { @Override public void onSubscribe(@NonNull Disposable d) { mView.showLoading(); } @Override public void onNext(@NonNull BaseObjectBean<LoginBean> loginBeanBaseObjectBean) { mView.onSuccess(loginBeanBaseObjectBean); System.out.println("onNext ----- >"); } @Override public void onError(@NonNull Throwable e) { mView.onError(e.getMessage()); mView.hideLoading(); } @Override public void onComplete() { mView.hideLoading(); }}); }}Copy the code
Specifically called in MainAbility
package com.example.hmsrxjava_demo; import com.example.hmsrxjava_demo.base.BaseMvpAbility; import com.example.hmsrxjava_demo.bean.BaseObjectBean; import com.example.hmsrxjava_demo.bean.LoginBean; import com.example.hmsrxjava_demo.contract.MainContract; import com.example.hmsrxjava_demo.presenter.MainPresenter; import ohos.agp.components.Button; import ohos.agp.components.Component; import ohos.agp.components.TextField; import ohos.agp.window.dialog.ToastDialog; public class MainAbility extends BaseMvpAbility<MainPresenter>implements MainContract.View { private TextField textUsername, textpasswrod; private String username, password; private Button loginBtn; private MainPresenter presenter; @Override public int getLayoutId() { return ResourceTable.Layout_ability_main; } @Override public void initView() { textUsername= (TextField) findComponentById(ResourceTable.Id_text_username); textpasswrod= (TextField) findComponentById(ResourceTable.Id_text_password); presenter=new MainPresenter(); presenter.attachView(this); loginBtn= (Button) findComponentById(ResourceTable.Id_login_btn); if(loginBtn! =null){ loginBtn.setClickedListener(new Component.ClickedListener() { @Override public void onClick(Component component) {system.out.println (" Click the login button "); username=textUsername.getText(); password=textpasswrod.getText(); if(username! =null&&password! =null){ presenter.login(username,password); // login(username,password); }else {new ToastDialog(MainAbility. This).settext (" account password cannot be empty ").show(); }}}); } } @Override public void onSuccess(BaseObjectBean<LoginBean> bean) { System.out.println(bean.getErrorCode()+bean.getErrorMsg()); new ToastDialog(MainAbility.this).setText(bean.getErrorCode()+bean.getErrorMsg()).show(); } @Override public void showLoading() { } @Override public void hideLoading() { } @Override public void onError(String errMessage) { } }Copy the code
The MVP+ Rxjava+Retrofit+ OKHTTP implementation tutorial is very similar to the android implementation and a lot of the code that I have here is copied and you can download the entire code and try it out
Conclusion:
MVP+ Rxjava+Retrofit+ OKHTTP is basically the same as android with a few surprises, For those of you who are not familiar with Rxjava+Retrofit+ OKHTTP, please check out the official tutorial and those of you who are not familiar with MVP mode, please check out my previous articles. There are also more about the implementation method of Hongmeng network programming students interested in private can try to achieve I will not expand on this side, finally HOPE my article can help you to solve the problem, I will contribute more useful code to share with you. If you think the article is good, please pay attention and star. Thank you
Project Address:
Yards cloud: gitee.com/qiuyu123/hm…