您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

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

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

问题是您试图同步返回的值enqueue,但是它是使用回调的异步方法,因此您无法做到这一点。您有2个选择:

大致如下所示:

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

这种方法的警告是,它只会将异步内容推上一个新的台阶,这可能对您来说是个问题。

看起来像:

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的框架。

其他 2022/1/1 18:14:50 有477人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶