You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Android中封装Retrofit调用并切换至主线程的最优方案

基于RxJava封装统一的机器信息API调用逻辑

1. 调整Retrofit接口定义

将原接口的Call返回类型替换为RxJava的Observable,让接口支持Rx链式操作:

@GET("/api/v1/smb/machines/{machineName}")
Observable<TLPJsonData<MachineData>> getMachineInfo(@Path("machineName") String machineName);

注意要确保Retrofit配置中添加了RxJava适配器,例如:

Retrofit retrofit = new Retrofit.Builder()
        // ...其他配置
        .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
        .build();

2. 创建统一的API管理类

这个类封装所有重复的网络请求逻辑、线程调度和错误处理:

public class MachineApiManager {
    private static MachineApiManager instance;
    private final SMBAPI smbApi;

    private MachineApiManager() {
        smbApi = SMBAPI.get();
    }

    public static MachineApiManager getInstance() {
        if (instance == null) {
            synchronized (MachineApiManager.class) {
                if (instance == null) {
                    instance = new MachineApiManager();
                }
            }
        }
        return instance;
    }

    // 封装机器信息获取逻辑
    public Observable<MachineData> fetchMachineInfo() {
        return smbApi.getMachineInfo(DeviceManager.getMachineName())
                // IO线程执行网络请求
                .subscribeOn(Schedulers.io())
                // 主线程接收回调
                .observeOn(AndroidSchedulers.mainThread())
                // 统一解析响应数据
                .map(tlpJsonData -> {
                    if (tlpJsonData.isSuccess()) {
                        return tlpJsonData.getData();
                    } else {
                        // 抛出业务异常
                        throw new ApiException(tlpJsonData.getCode(), tlpJsonData.getMessage());
                    }
                })
                // 统一捕获所有异常
                .onErrorResumeNext(throwable -> {
                    String errorMsg;
                    if (throwable instanceof ApiException) {
                        errorMsg = throwable.getMessage();
                    } else if (throwable instanceof IOException) {
                        errorMsg = "网络连接失败,请检查网络";
                    } else {
                        errorMsg = "数据解析错误";
                    }
                    return Observable.error(new ApiException(-1, errorMsg));
                });
    }
}

// 自定义异常类,用于传递业务错误信息
class ApiException extends Exception {
    private int code;

    public ApiException(int code, String message) {
        super(message);
        this.code = code;
    }

    public int getCode() {
        return code;
    }
}

3. 简化后的调用示例

任何需要获取机器信息的地方,只需调用统一方法,专注处理业务结果即可:

MachineApiManager.getInstance().fetchMachineInfo()
        .subscribe(
                machineData -> {
                    // 处理成功获取的机器数据
                    updateMachineUI(machineData);
                },
                throwable -> {
                    // 统一处理错误提示
                    Toast.makeText(getApplicationContext(), throwable.getMessage(), Toast.LENGTH_SHORT).show();
                }
        );

核心优势

  • 消除重复代码:所有网络请求的模板逻辑(线程切换、响应解析)都集中在管理类中,调用点无需重复编写
  • 统一错误处理:所有异常(网络错误、业务错误、解析错误)都在一处处理,避免每个调用点重复判断
  • 线程自动调度:默认完成IO线程请求、主线程回调的切换,无需手动管理Handler或AsyncTask
  • 易扩展:后续如需添加缓存、重试、日志等逻辑,只需修改MachineApiManager即可全局生效

内容的提问来源于stack exchange,提问作者Rich Morey

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.03 17:40:16