【问题标题】:Manage multiple Retrofit calls such that update UI based on last API call and cancel previous calls管理多个 Retrofit 调用,以便根据上次 API 调用更新 UI 并取消以前的调用
【发布时间】:2017-12-25 07:39:17
【问题描述】:

我使用 Retrofit2 获取在地图上选择的指定位置的信息,并通过调用方法 getLabelFromServer 将其显示在我的应用程序 UI 上,如下所示。

由于用户可能会在我等待从服务器接收信息时更改所选位置,因此我应该取消先前对接收到的信息的调用并等待接收新位置的信息并在响应新调用时更新 UI。 请注意,先前的调用不应更新 UI,因为它将显示用户现在未选择的先前位置的信息。 如何更改下面的代码来实现这一点(我应该注意,每次在地图上选择新位置时,我都会在 UI 线程上调用此方法)。

 private void getLabelFromServer(Context ctx, GeoPoint geoPoint) {
    MapServiceGenerator serviceGenerator = MapServiceGenerator.getInstance(ctx, null);
    Call<JsonObject> call = serviceGenerator.getGeoCodeApi().getAddress(geoPoint.getLatitude() + "," + geoPoint.getLongitude());
    call.enqueue(new Callback<JsonObject>() {
                     @Override
                     public void onResponse(Call<JsonObject> call, Response<JsonObject> response) {
                         JsonObject result = response.body();
                         String positionLabel = MapUtils.generateLabelFromJSON(result);
                         tvLabel.setText(positionLabel);
                     }

                     @Override
                     public void onFailure(Call<JsonObject> call, Throwable t) {
                         if (t != null) {
                             t.printStackTrace();
                         } 
                     }
                 }
    );
}

【问题讨论】:

  • 检查 call.isExecuted();发出下一个请求之前的方法。如果返回 true,则您的请求已完成。

标签: android google-maps concurrency retrofit2


【解决方案1】:

检查 call.isExecuted();发出下一个请求之前的方法。 如果它返回 true,则您的请求已完成。 否则,它还没有完成,所以调用 call.cancel() 方法取消请求并重新发起你的请求

【讨论】:

  • 你知道吗,如果此刻call.isExecuted() 为真,我打电话给call.cancel() 会是什么结果?它会引发异常还是会毫无问题地运行?
猜你喜欢
  • 2014-02-03
  • 1970-01-01
  • 2013-05-30
  • 2018-06-29
  • 1970-01-01
  • 1970-01-01
  • 2021-04-04
  • 1970-01-01
  • 2015-08-15
相关资源
最近更新 更多