改造:如何等待响应

2022-09-03 13:10:03

我有AsyncTask和doInBackground方法,其中,我使用Retrofit发送POST请求。我的代码看起来像这样:

    //method of AsyncTask
    protected Boolean doInBackground(Void... params) {
        Retrofit restAdapter = new Retrofit.Builder()
                .baseUrl(Constants.ROOT_API_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        IConstructSecureAPI service = restAdapter.create(IConstructSecureAPI.class);
        //request
        Call<JsonElement> result = service.getToken("TestUser", "pass", "password");
        result.enqueue(new Callback<JsonElement>() {
            @Override
            public void onResponse(Call<JsonElement> call, Response<JsonElement> response) {

            }

            @Override
            public void onFailure(Call<JsonElement> call, Throwable t) {

            }
        });

        return true;
    }

问题是:改造异步发送请求,同时,doInBackground方法返回值。因此,我需要在同一线程中发送一个请求,其中包含序列中的所有执行。一个接一个。从 doInBackground 返回发生在请求完成后。如何使用改造在同一线程中发送请求?


答案 1

该类具有一个 execute() 方法,该方法将同步进行调用。Call

enqueue()明确用于进行异步调用。


答案 2

“异步改造发送请求”,正如@Tanis.7x所提到的,enqueue()正在执行异步,那么有什么理由放入AsyncTask?(异步中的异步 ?

您只需将所有改造代码从 AsyncTask 中取出,并且是等待请求调用返回的回调,因此您可以在此回调中执行任何 UI 更新。onResponse


推荐