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

RxJava和Retrofit2的统一处理单个请求示例详解

程序员文章站 2023-10-30 17:14:52
前言 rxjava和retrofit2用了一段时间了,写个小例子,分享出来,有什么不对的地方还请大神在评论区指正。 什么是retrofit2 官网是这么介绍的...

前言

rxjava和retrofit2用了一段时间了,写个小例子,分享出来,有什么不对的地方还请大神在评论区指正。

什么是retrofit2

官网是这么介绍的:

retrofit adapts a java interface to http calls by using annotations on the declared methods to
define how requests are made。

我翻译的可能不准确,他的大概意思是说:retrofit 是一个 java 接口类,以注解的方式用于 http 网络请求。那下面我们一起来看看是怎么使用的?

发现问题

最近在帮兄弟公司做一个资讯类的项目,使用了rxjava和retrofit2这对黄金组合,在编写代码的过程中发现有很多很多的网络请求都需要做.subscribeon(schedulers.io()).observeon(androidschedulers.mainthread()).onerrorreturn()的处理,为避免这样,需要沉思。

解决问题

import android.util.log;

import com.wei.caiqiwang.data.entity.baseresponse;

import rx.observable;
import rx.subscriber;
import rx.subscription;
import rx.android.schedulers.androidschedulers;
import rx.functions.func1;
import rx.schedulers.schedulers;

public class rxnet {
 /**
  * 统一处理单个请求
  */
 public static <t> subscription request(observable<baseresponse<t>> observable, final rxnetcallback<t> callback) {
  return observable
    .subscribeon(schedulers.io())
    .observeon(androidschedulers.mainthread())
    .onerrorreturn(new func1<throwable, baseresponse<t>>() {
     @override
     public baseresponse<t> call(throwable throwable) {
      log.v("linneterror",throwable.getmessage());
      callback.onfailure(exceptionhandle.handleexception(throwable));
      return null;
     }
    })
    .subscribe(new subscriber<baseresponse<t>>() {
     @override
     public void oncompleted() {

     }

     @override
     public void onerror(throwable e) {

     }

     @override
     public void onnext(baseresponse<t> baseresponse) {
      if (baseresponse.getcode().equals("200")) {
       callback.onsuccess(baseresponse.getdata());
      } else {
       callback.onfailure(baseresponse.getmsg());
      }
     }
    });

 }

 /**
  * 统一处理单个请求没有 msg body
  */
 public static subscription requestwithoutbody(observable<baseresponse> observable, final rxnetcallback<string> callback) {
  return observable
    .subscribeon(schedulers.io())
    .observeon(androidschedulers.mainthread())
    .onerrorreturn(new func1<throwable, baseresponse>() {
     @override
     public baseresponse call(throwable throwable) {
      callback.onfailure(exceptionhandle.handleexception(throwable));
      return null;
     }
    })
    .subscribe(new subscriber<baseresponse>() {
     @override
     public void oncompleted() {

     }

     @override
     public void onerror(throwable e) {

     }

     @override
     public void onnext(baseresponse baseresponse) {
      if (baseresponse.getcode().equals("200")) {
       callback.onsuccess(baseresponse.getmsg());
      } else {
       callback.onfailure(baseresponse.getmsg());
      }
     }
    });

 }
}

回调就是普通的回调

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

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

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

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:

import android.util.log;


import com.wei.demo.data.appconstants;

import java.util.concurrent.timeunit;

import okhttp3.okhttpclient;
import okhttp3.logging.httplogginginterceptor;
import retrofit2.retrofit;
import retrofit2.adapter.rxjava.rxjavacalladapterfactory;
import retrofit2.converter.gson.gsonconverterfactory;

public class apimanager {

 private retrofit client;

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

 private static volatile demoapi instance;

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

 private demoapi getapi() {
  return client.create(demoapi.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("netlog", message);
   }
  });
  //设定日志级别
  httplogginginterceptor.setlevel(httplogginginterceptor.level.body);
  //延时
  builder.addinterceptor(httplogginginterceptor)
    .connecttimeout(10, timeunit.seconds)
    .readtimeout(10, timeunit.seconds)
    .writetimeout(10, timeunit.seconds);
  return builder.build();
 }
}

怎么用?

 rxnet.request(apimanager.getinstance().getusermsg(map), new rxnetcallback<list<msgbean>>() {
   @override
   public void onsuccess(list<msgbean> data) {
    // 处理数据
   }

   @override
   public void onfailure(string msg) {
    //出现了错误
    showtoast(msg);
    
   }
  });

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

总结

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