我怎样才能从 Retrofit 的 onResponse 函数中获得 return 值?

How can I return value from function onResponse of Retrofit?

我正在尝试 return 我从 retrofit 调用请求中的 onResponse 方法获得的值,有没有办法可以从覆盖的方法?这是我的代码:

public JSONArray RequestGR(LatLng start, LatLng end)
    {
       final JSONArray jsonArray_GR;

        EndpointInterface loginService = ServiceAuthGenerator.createService(EndpointInterface.class);    
        Call<GR> call = loginService.getroutedriver();
        call.enqueue(new Callback<GR>() {
            @Override
            public void onResponse(Response<GR> response , Retrofit retrofit)
            {

                 jsonArray_GR = response.body().getRoutes();
//i need to return this jsonArray_GR in my RequestGR method
            }
            @Override
            public void onFailure(Throwable t) {
            }
        });
        return jsonArray_GR;
    }

我无法获得 jsonArray_GR 的值,因为为了能够在 onResponse 方法中使用它,我需要将其声明为 final 并且我无法为其赋值。

问题是您正在尝试同步 return enqueue 的值,但它是一种使用回调的异步方法,因此您不能这样做。您有 2 个选择:

  1. 您可以更改 RequestGR 方法以接受回调,然后将 enqueue 回调链接到它。这类似于 rxJava 等框架中的映射。

大致如下:

public void RequestGR(LatLng start, LatLng end, final Callback<JSONArray> arrayCallback)
    {

        EndpointInterface loginService = ServiceAuthGenerator.createService(EndpointInterface.class);    
        Call<GR> call = loginService.getroutedriver();
        call.enqueue(new Callback<GR>() {
            @Override
            public void onResponse(Response<GR> response , Retrofit retrofit)
            {

                 JSONArray jsonArray_GR = response.body().getRoutes();
                 arrayCallback.onResponse(jsonArray_GR);
            }
            @Override
            public void onFailure(Throwable t) {
               // error handling? arrayCallback.onFailure(t)?
            }
        });
    }

这种方法的警告是它只是将异步的东西推到另一个层次,这对你来说可能是个问题。

  1. 您可以使用类似于 BlockingQueuePromiseObservable 的对象,甚至您自己的容器对象(注意线程安全),它允许您检查并设置值。

这看起来像:

public BlockingQueue<JSONArray> RequestGR(LatLng start, LatLng end)
    {
        // You can create a final container object outside of your callback and then pass in your value to it from inside the callback.
        final BlockingQueue<JSONArray> blockingQueue = new ArrayBlockingQueue<>(1);
        EndpointInterface loginService = ServiceAuthGenerator.createService(EndpointInterface.class);    
        Call<GR> call = loginService.getroutedriver();
        call.enqueue(new Callback<GR>() {
            @Override
            public void onResponse(Response<GR> response , Retrofit retrofit)
            {

                 JSONArray jsonArray_GR = response.body().getRoutes();
                 blockingQueue.add(jsonArray_GR);
            }
            @Override
            public void onFailure(Throwable t) {
            }
        });
        return blockingQueue;
    }

然后您可以像这样在调用方法中同步等待结果:

BlockingQueue<JSONArray> result = RequestGR(42,42);
JSONArray value = result.take(); // this will block your thread

尽管如此,我还是强烈建议阅读像 rxJava 这样的框架。