简体   繁体   English

网络通话结束时Java同步返回

[英]Java synchronized return when a network call finishes

I have a method intercept which expects a Response object in return. 我有一个方法intercept ,期望返回一个Response对象。

@Override
public Response intercept(Interceptor.Chain chain) throws IOException {
    Request original = chain.request();
    mRequestBuilder = original.newBuilder();

    mAgent.getToken(new OnTokenResponse() {
        @Override
        public void onSuccess(final String token) {
            mRequestBuilder.removeHeader(AUTHORIZATION);
            mRequestBuilder.header(AUTHORIZATION, "Bearer " + token);
        }

        @Override
        public void onFailure(final String error) {

        }
    });

    Request request = mRequestBuilder.build();
    return chain.proceed(request);
}

mAgent.getToken() makes a network call and returns a string in onSuccess if succeeded. mAgent.getToken()进行网络调用,如果成功,则在onSuccess中返回一个字符串。 Which in turn, I add as header to mRequestBuilder . 反过来,我将其添加为mRequestBuilder标头。 Now since, the network call will take some time to finish, I want to execute Request request = mRequestBuilder.build() only after the network call is completed (either success or failure). 现在,网络调用将花费一些时间才能完成,我只想在网络调用完成(成功或失败)之后执行Request request = mRequestBuilder.build() )。

How can I synchronize this operation? 如何同步此操作?

I want to execute Request request = mRequestBuilder.build() only after the network call is completed (either success or failure). 我只想在网络调用完成(成功或失败)之后执行Request request = mRequestBuilder.build() )。

How can I synchronize this operation? 如何同步此操作?

You either wait (block) until the network call completed, or you do request = mRequestBuilder.build();... in the callback itself. 您可以等待(阻止)直到网络调用完成,或者在回调本身中执行request = mRequestBuilder.build();...

Waiting/blocking is not a good idea if you do it on the main/GUI thread. 如果在主/ GUI线程上进行等待/阻塞,则不是一个好主意。

Running code inside the callback is probably not a good idea too, because the callback probably runs in some networking thread, and you definitely should not call chain.proceed() on that thread. 在回调内部运行代码可能也不是一个好主意,因为回调可能在某个网络线程中运行,并且您绝对不应在该线程上调用chain.proceed()

So the only clean way to do it is to run the network request at some appropriate point/time to obtain the result first, and only after that result is available allow the code to be called that depends on it. 因此,唯一的干净方法是在某个适当的时间点运行网络请求以首先获得结果,并且只有在该结果可用后才允许调用依赖于此的代码。

I deliberately don't include an example of how to block waiting for a signal from an asynchronous callback here because you really shouldn't use this kind of blocking if it might happen to run on the GUI thread. 我故意在此处不提供有关如何阻止等待来自异步回调的信号的示例,因为如果它可能恰好在GUI线程上运行,则您实际上不应该使用这种阻止。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM