赞
踩
RxJava的作用主要就是负责线程调度,所以就可以把Retrofit封装为一个工具类;主要代码如下:
-
- import android.support.annotation.NonNull;
- import com.jakewharton.retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
- import java.util.concurrent.TimeUnit;
- import okhttp3.OkHttpClient;
- import retrofit.ApiUrl;
- import retrofit.Constans;
- import retrofit2.Retrofit;
- import retrofit2.converter.gson.GsonConverterFactory;
- /**
- * Retrofit封装
- */
- public class RetrofitUtils {
- private static final String TAG = "RetrofitUtils";
- private static ApiUrl mApiUrl;
- /**
- * 单例模式
- */
- // 主要就是调用这个方法获得Retrofit的接口服务对象
- public static ApiUrl getApiUrl() {
- if (mApiUrl == null) {
- synchronized (RetrofitUtils.class) {
- if (mApiUrl == null) {
- mApiUrl = new RetrofitUtils().getRetrofit();
- }
- }
- }
- return mApiUrl;
- }
- private RetrofitUtils(){}
-
- public ApiUrl getRetrofit() {
- // 初始化Retrofit
- ApiUrl apiUrl = initRetrofit(initOkHttp()) .create(ApiUrl.class);
- return apiUrl;
- }
-
- /**
- * 初始化Retrofit
- */
- @NonNull
- private Retrofit initRetrofit(OkHttpClient client) {
- return new Retrofit.Builder()
- .client(client)
- .baseUrl(Constans.BaseUrl)
- .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
- .addConverterFactory(GsonConverterFactory.create())
- .build();
- }
-
- /**
- * 初始化okhttp
- */
- @NonNull
- private OkHttpClient initOkHttp() {
- return new OkHttpClient().newBuilder()
- .readTimeout(Constans.DEFAULT_TIME, TimeUnit.SECONDS)//设置读取超时时间
- .connectTimeout(Constans.DEFAULT_TIME, TimeUnit.SECONDS)//设置请求超时时间
- .writeTimeout(Constans.DEFAULT_TIME,TimeUnit.SECONDS)//设置写入超时时间
- .addInterceptor(new LogInterceptor())//添加打印拦截器
- .retryOnConnectionFailure(true)//设置出现错误进行重新连接。
- .build();
- }
- }
-

定义Retrofit的服务接口:
- public interface WeatherApi {
- @GET("101210101.html")
- Single<Weather> getWeather();
- }
在ViewModel中定义网络访问服务器接口的方法
- public void getWeather2(){
- RetrofitUtils
- .getApiService()
- .getWeather()
- .subscribeOn(Schedulers.io())
- .observeOn(AndroidSchedulers.mainThread())
- .subscribe(weather -> weatherMutableLiveData.setValue(weather.getWeatherinfo()));
- }
在Activity/Fragment中给ViewModel中的LiveData添加观察者,在需要获取网络数据的地方通过ViewModel对象调用getWeather()方法 weatherVM.getWeather2()即可,然后获取网络数据成功后LiveData就会通知数据改变,然后dataBinding框架就会自动刷新页面.
添加观察者:
- //LiveData的observer为这个activity,只有当activity还存活的时候才会收到数据更新的通知
- weatherVM.getWeatherMutableLiveData().observe(this,this::updata);
-
-
-
- //在观察者数据更新回调中调用这个方法告诉DataBinding数据更新以刷新UI页面
- private void updata(Weather.WeatherinfoBean weatherinfoBean) {
- activityMainBinding.setWeatherinfo(weatherinfoBean);
- }
通过DataBinding绑定天气数据实体类WeatherInfoBean, 这样就实现了一个简单的MVVM模式架构.
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。