改进"IllegalStateException:已执行". [英] Retrofit "IllegalStateException: Already executed"

查看:87
本文介绍了改进"IllegalStateException:已执行".的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个改造网络电话,该ID希望每5秒运行一次.我当前的代码:

I have a Retrofit network call that id like to run every 5 seconds. My current code:

Handler h = new Handler();
int delay = 5000; //milliseconds

h.postDelayed(new Runnable() {
    public void run() {
        call.enqueue(new Callback<ApiResponse>() {
            @Override
            public void onResponse(Response<ApiResponse> response) {
                Log.d("api", "response: " + response.body().getPosition().getLatitude().toString());
            }

            @Override
            public void onFailure(Throwable t) {

            }
        });
        h.postDelayed(this, delay);
    }
}, delay);

这将运行一次,但是会引发以下内容:

This runs once, but then throws the following:

java.lang.IllegalStateException:已执行. 在retrofit2.OkHttpCall.enqueue(OkHttpCall.java:52) 在retrofit2.ExecutorCallAdapterFactory $ ExecutorCallbackCall.enqueue(ExecutorCallAdapterFactory.java:57) 在orbyt.project.MyFragment $ 1.run(MyFragment.java:93)

java.lang.IllegalStateException: Already executed. at retrofit2.OkHttpCall.enqueue(OkHttpCall.java:52) at retrofit2.ExecutorCallAdapterFactory$ExecutorCallbackCall.enqueue(ExecutorCallAdapterFactory.java:57) at orbyt.project.MyFragment$1.run(MyFragment.java:93)

这里有什么问题?

作为奖励:解决这个问题的更好方法是什么?每次更新都会更新地图.我当时正在考虑尝试使用Rx,但不确定这是否是合适的用例,或者如何实现.

As a bonus: whats a better way to handle this? Ill be updating a map every update. I was thinking about trying to use Rx but not sure if this is an appropriate use-case, or how to implement it.

推荐答案

Call只能使用一次. 其文档告诉您如何多次使用:

A Call can only be used once. Its documentation tells you how to use one multiple times:

使用clone()对相同的Web服务器进行具有相同参数的多个调用;这可用于实施轮询或重试失败的呼叫.

Use clone() to make multiple calls with the same parameters to the same webserver; this may be used to implement polling or to retry a failed call.

因此,分别将call.clone().enqueue(..)用于异步,将call.clone().execute()分别用于 Synchornous ,以确保您拥有未执行的全新Call每个请求.

So use call.clone().enqueue(..) for Asynchornous and call.clone().execute() for Synchornous respectively to ensure that you have a fresh, unexecuted Call for each request.

这篇关于改进"IllegalStateException:已执行".的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆