欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

RxJava2和Retrofit2封装教程(整洁、简单、实用)

程序员文章站 2022-06-04 12:13:12
前言 rxjava2与retrofit2是老搭档了,之前写了一篇《rxjava和retrofit2的统一处理单个请求》,是用的rxjava1.0,本次使用rxjava2....

前言

rxjava2与retrofit2是老搭档了,之前写了一篇《rxjava和retrofit2的统一处理单个请求》,是用的rxjava1.0,本次使用rxjava2.0与retrofit2进行封装,一样整洁、简单、实用。rxjava2相比rxjava1优化和改动不少了东西,网上有很多大神写的文章,这里就不粘贴复制了。封装的过程有什么问题、疑问,请在下方留言。

下面话不多说了,来一起看看详细的介绍吧

封装教程如下:

核心网络请求:

package com.lin.netrequestdemo.data;


import android.util.log;

import io.reactivex.observable;
import io.reactivex.android.schedulers.androidschedulers;
import io.reactivex.disposables.disposable;
import io.reactivex.functions.consumer;
import io.reactivex.functions.function;
import io.reactivex.schedulers.schedulers;

public class rxnet {
 /**
 * 统一处理单个请求
 *
 * @param observable
 * @param callback
 * @param <t>
 */
 public static <t> disposable request(observable<baseresponse<t>> observable, final rxnetcallback<t> callback) {
 return observable.subscribeon(schedulers.io())
  .observeon(androidschedulers.mainthread())
  .onerrorreturn(new function<throwable, baseresponse<t>>() {
   @override
   public baseresponse<t> apply(throwable throwable) {
   log.e("linneterror", throwable.getmessage());
   callback.onfailure(exceptionhandle.handleexception(throwable));
   return null;
   }
  })
  .subscribe(new consumer<baseresponse<t>>() {
   @override
   public void accept(baseresponse<t> tbaseresponse) {
   if (tbaseresponse.getcode().equals("200")) {
    callback.onsuccess(tbaseresponse.getdata());

   } else {
    callback.onfailure(tbaseresponse.getmsg());
   }
   }
  }, new consumer<throwable>() {
   @override
   public void accept(throwable throwable) {
   log.e("linneterror", "单个请求的错误" + throwable.getmessage());
   }
  });
 }

 /**
 * 统一处理单个请求
 * 返回数据没有body
 */
 public static disposable requestwithoutbody(observable<baseresponse> observable,
      final rxnetcallback<string> callback) {
 return observable.subscribeon(schedulers.io())
  .observeon(androidschedulers.mainthread())
  .onerrorreturn(new function<throwable, baseresponse>() {
   @override
   public baseresponse apply(throwable throwable) {
   log.v("linneterror", throwable.getmessage());
   callback.onfailure(exceptionhandle.handleexception(throwable));
   return null;
   }
  })
  .subscribe(new consumer<baseresponse>() {
   @override
   public void accept(baseresponse baseresponse) {
   if (baseresponse.getcode().equals("200")) {
    callback.onsuccess(baseresponse.getmsg());
   } else {
    callback.onfailure(baseresponse.getmsg());
   }
   }
  }, new consumer<throwable>() {
   @override
   public void accept(throwable throwable) {
   log.v("linneterror", "单个请求的错误:没有body" + throwable.getmessage());
   }
  });

 }
}

回调就是普通的泛型的回调

package com.lin.netrequestdemo.data;


public interface rxnetcallback<t> {
 /**
 * 数据请求成功
 *
 * @param data 请求到的数据
 */
 void onsuccess(t data);

 /**
 * 数据请求失败
 */
 void onfailure(string msg);
}

错误异常处理(可能不全):

package com.lin.netrequestdemo.data;

import android.net.parseexception;

import com.google.gson.jsonparseexception;


import org.apache.http.conn.connecttimeoutexception;
import org.json.jsonexception;

import java.net.connectexception;

import retrofit2.httpexception;


public class exceptionhandle {

 private static final int unauthorized = 401;
 private static final int forbidden = 403;
 private static final int not_found = 404;
 private static final int request_timeout = 408;
 private static final int internal_server_error = 500;
 private static final int bad_gateway = 502;
 private static final int service_unavailable = 503;
 private static final int gateway_timeout = 504;

 public static string handleexception(throwable e) {
 string errormsg;
 if (e instanceof httpexception) {
  httpexception httpexception = (httpexception) e;
  switch (httpexception.code()) {
  case unauthorized:
  case forbidden:
  case not_found:
  case request_timeout:
  case gateway_timeout:
  case internal_server_error:
  case bad_gateway:
  case service_unavailable:
  default:
   errormsg = "网络错误";
   break;
  }
  return errormsg + ":" + httpexception.code();
 } else if (e instanceof jsonparseexception || e instanceof jsonexception || e instanceof parseexception) {
  return "解析错误";
 } else if (e instanceof connectexception) {
  return "连接失败";
 } else if (e instanceof javax.net.ssl.sslhandshakeexception) {
  return "证书验证失败";
 } else if (e instanceof connecttimeoutexception) {
  return "连接超时";
 } else if (e instanceof java.net.sockettimeoutexception) {
  return "连接超时";
 } else {
  return "未知错误";
 }
 }

}

然后就是apimanager:

package com.lin.netrequestdemo.data.api;

import android.util.log;

import com.lin.netrequestdemo.data.appconstants;

import java.util.concurrent.timeunit;

import okhttp3.okhttpclient;
import okhttp3.logging.httplogginginterceptor;
import retrofit2.retrofit;
import retrofit2.adapter.rxjava2.rxjava2calladapterfactory;
import retrofit2.converter.gson.gsonconverterfactory;


public class apimanager {

 private retrofit client;

 private apimanager() {
 client = new retrofit.builder()
  .baseurl(appconstants.base_url_test)
  .client(initclient())
  .addcalladapterfactory(rxjava2calladapterfactory.create())
  .addconverterfactory(gsonconverterfactory.create())
  .build();
 }

 private static volatile mallapi instance;

 public static mallapi getinstance() {
 if (instance == null) {
  synchronized (apimanager.class) {
  if (instance == null) {
   instance = new apimanager().getmallapi();
  }
  }
 }
 return instance;
 }

 private mallapi getmallapi() {
 return client.create(mallapi.class);
 }

 private static okhttpclient initclient() {
 okhttpclient.builder builder = new okhttpclient.builder();
 //声明日志类
 httplogginginterceptor httplogginginterceptor = new httplogginginterceptor(new httplogginginterceptor.logger() {
  @override
  public void log(string message) {
  log.v("linnet", message);
  }
 });
 //设定日志级别
 httplogginginterceptor.setlevel(httplogginginterceptor.level.body);
 //延时
 builder.addinterceptor(httplogginginterceptor)
  .connecttimeout(10, timeunit.seconds)
  .readtimeout(10, timeunit.seconds)
  .writetimeout(10, timeunit.seconds);
 return builder.build();
 }

}

怎么用:

showloading();
 map<string, string> map = new arraymap<>();
 map.put("action", "pricetrend");
 addcompositedisposable(rxnet.request(apimanager.getinstance().getcat(map), new rxnetcallback<list<catbean>>() {
  @override
  public void onsuccess(list<catbean> data) {
  hideloading();
  showtoast("获取列表成功" + data.get(0).tostring());
  }

  @override
  public void onfailure(string msg) {
  hideloading();
  showtoast(msg);
  }
 }));

demo奉上 https://github.com/friendlin/netrequestdemo本地下载

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,如果有疑问大家可以留言交流,谢谢大家对的支持。