如何从改造的onResponse函数返回值?

克里斯蒂安·卡姆(Cristian Cam G)

我正在尝试返回我从调用请求中的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方法中使用它,我需要将其声明为最终值,而我无法给它赋值。

托尔宾斯基

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章