1.http(工具类)
public class RetrofitManager {
private Retrofit mretrofit;
//私有构造
private RetrofitManager(){
}
//声明变量
private static RetrofitManager retrofitManager=null;
//对外提供接口
public static RetrofitManager getInstance(){
if(retrofitManager==null){
retrofitManager=new RetrofitManager();
}
return retrofitManager;
}
public Retrofit getRetrofit(){
if(mretrofit==null){
mretrofit=createRetrofit();
}
return mretrofit;
}
private Retrofit createRetrofit() {
//拦截器
OkHttpClient client=new OkHttpClient.Builder()
.connectTimeout(5, TimeUnit.MINUTES)
.writeTimeout(5,TimeUnit.MINUTES)
.readTimeout(5,TimeUnit.MINUTES)
.addInterceptor(new HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY))
.build();
mretrofit=new Retrofit.Builder()
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.client(client)
.baseUrl("http://10.161.9.80:7012/")
.build();
return mretrofit;
}
}
2.Api
public interface Api {
@GET("/foods/getFoods")
Observable<FoodEntity> getFoodData(@Query("currentPage") int currentPage,@Query("pageSize")int pageSize);
}
3.ViewModel
public class FoodViewModel extends ViewModel {
private FoodModel mfoodModel;
public MutableLiveData<FoodEntity> foodLiveData=new MutableLiveData<>();
public FoodViewModel() {
mfoodModel=new FoodModel();
}
public void getFood(int currentPage,int pageSize){
mfoodModel.getFoodData(currentPage,pageSize)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Observer<FoodEntity>() {
@Override
public void onSubscribe(Disposable d) {
}
@Override
public void onNext(FoodEntity foodEntity) {
Log.d("sss", "onNext: "+foodEntity.getCode());
foodLiveData.postValue(foodEntity);
}
@Override
public void onError(Throwable e) {
}
@Override
public void onComplete() {
}
});
}
}
4.View
public class FoodActivity extends AppCompatActivity {
ActivityFoodBinding activityFoodBinding;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.activity_food);
activityFoodBinding= DataBindingUtil.setContentView(this,R.layout.activity_food);
FoodViewModel foodViewModel=new ViewModelProvider(this).get(FoodViewModel.class);
//启动mvvm
foodViewModel.getFood(1,10);
}
}
5.model
public class FoodModel {
protected Api mapi;
public FoodModel() {
mapi= RetrofitManager.getInstance().getRetrofit().create(Api.class);
}
public Observable<FoodEntity> getFoodData( int currentPage,int pageSize){
return mapi.getFoodData(currentPage,pageSize);
}
}
————————————————
版权声明:本文为CSDN博主「懒得热情0914」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/2301_79998448/article/details/134913177