如何从函数onResponse of Retrofit返回值?

问题描述 投票:5回答:1

我试图在onResponse调用请求中返回我从retrofit方法得到的值,有没有办法可以从覆盖方法中获取该值?这是我的代码:

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方法中使用它我需要声明它最终,我不能给它一个值。

java json methods retrofit
1个回答
13
投票

问题是你试图同步返回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这样的框架。

© www.soinside.com 2019 - 2024. All rights reserved.