改造 "IllegalStateException: Already executed"

Retrofit "IllegalStateException: Already executed"

我有一个 ID 喜欢每 5 秒 运行 的 Retrofit 网络调用。我当前的代码:

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);

这 运行s 一次,但随后抛出以下内容:

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

这里有什么问题?

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

一个Call只能使用一次。 Its documentation告诉你如何多次使用一个:

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.

因此,对 Asynchornous 使用 call.clone().enqueue(..),对 Synchornous 使用 call.clone().enqueue(..) 以确保每个请求都有一个全新的、未执行的 Call