【问题标题】:Retrofit 2.0 - Custom CallAdapterFactory - Callbacks not happening on MainThreadRetrofit 2.0 - 自定义 CallAdapterFactory - MainThread 上未发生回调
【发布时间】:2016-11-24 22:58:56
【问题描述】:

我正在将我的 Android 应用程序迁移到 Retrofit 2.0。我有一个扩展 RetrofitError 的自定义 ErrorHandler,所以我可以对不同的 Http 错误做出反应。

现在我知道我必须创建一个自定义 CallAdapterFactory。我使用了ErrorHandlingCallAdapter 提供的样本here

我生成的 CallAdapter 几乎是相同的代码,但如果需要我也可以发布我的代码。

发生的事情是,当我使用这个CallAdapterFactory 时,MainThread 上没有发生回调。我在尝试更新 UI 时收到 android.view.ViewRootImpl$CalledFromWrongThreadException(我总是需要这样做)。我也不想总是在我的回调中使用 runOnUIThread 包装我的代码。

我不知道这是否有帮助,但是当我在回调中记录 Thread.currentThread().getName() 时,它会返回 OkHttp。

【问题讨论】:

    标签: android retrofit


    【解决方案1】:

    我最终将执行程序传递给我的 CallAdapter.Factory:

    public static class MainThreadExecutor implements Executor {
        private final Handler handler = new Handler(Looper.getMainLooper());
    
        @Override
        public void execute(@NonNull Runnable r) {
            handler.post(r);
        }
    }
    

    ...

    .addCallAdapterFactory(new ErrorHandlingCallAdapter.ErrorHandlingCallAdapterFactory(new MainThreadExecutor()))
    

    并将回调包装在:

    callbackExecutor.execute(new Runnable() {
        @Override
        public void run() {
        }
    });
    

    我的灵感来自this

    【讨论】:

      【解决方案2】:

      你不需要创建一个新的执行器,你可以使用改造的:

      public AuthCall adapt(Call call) {
          return new CustomCall(call, statuses, retrofit.callbackExecutor());
      }
      

      在您改编的调用中保留它的引用,然后在您的回调中使用它:

      customCall.enqueue(new Callback() {
          executor.execute(...
      

      【讨论】:

        猜你喜欢
        • 2019-12-28
        • 1970-01-01
        • 1970-01-01
        • 2013-06-02
        • 2019-05-06
        • 1970-01-01
        • 2012-04-22
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多