在继续异步之前等待retrofit2完成的最佳方法

Hap*_*rel 5 android asynchronous countdownlatch runnable retrofit2

我意识到类似的问题已被问到,但我是android的新手,并且发现答案有点令人困惑,因为它们的情况略有不同.

我查看了CountDownLatch以及使用Threads,我不确定使用哪种方法.任何帮助将非常感激.我也尝试使用apply()而不是commit()来实现SharedPreferences.

我正在从LoginActivity进行2次retrofit2调用.我需要第一次调用中的令牌才能在第二次调用中使用.我将令牌保存到第一次改装调用的onResponse方法的sharedpreferences中的字符串.

在我的第二次调用中,serverToken的值将作为在应用程序的上一次运行中设置的令牌返回

第一次调用(getToken)onResponse

   call.enqueue(new retrofit2.Callback<TokenResponse>() {    

            @Override
            public void onResponse(Call<TokenResponse> call, retrofit2.Response<TokenResponse> response) {

                if (response.isSuccessful()) {
                    TokenResponse tokenResponse = response.body();

                    LoginActivity.editor.putString("serverToken", tokenResponse.getAccessToken());
                    LoginActivity.editor.commit();

                } else {
                    Log.i("Server Token", "failed");
                }
            }
 }
Run Code Online (Sandbox Code Playgroud)

LoginActivity

public class LoginActivity extends AppCompatActivity {

    public static SharedPreferences preferences;
    public static SharedPreferences.Editor editor;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        authenticationController = new AuthenticationController();
        preferences = PreferenceManager.getDefaultSharedPreferences(this);
        editor = preferences.edit();
    }

    public void onLoginClicked(View view) {
        getToken();    //FIRST RETROFIT CALL
        connectToPush(); //SECOND CALL WHERE I NEED TOKEN FROM FIRST CALL
    }

    public void getToken() {
        authenticationController.login(grantType, username, password);
    }

    public void connectToPush() {
        authenticationController.connectToPush();
    }
Run Code Online (Sandbox Code Playgroud)

我的第二次改造电话

public void connectToPush(){

  Log.i("sharedpreferencesToken", LoginActivity.preferences.getString("serverToken", "null serverToken"));

}
Run Code Online (Sandbox Code Playgroud)

Hap*_*rel 0

好吧,我最终找到了解决方案。在改造github上找到了答案
“使用方法1的回调来触发方法2”
我将connectToPush()移至第一次调用的onResponse。

  call.enqueue(new retrofit2.Callback<TokenResponse>() {    

            @Override
            public void onResponse(Call<TokenResponse> call, retrofit2.Response<TokenResponse> response) {

                if (response.isSuccessful()) {


               TokenResponse tokenResponse = response.body();

                LoginActivity.editor.putString("serverToken", tokenResponse.getAccessToken());
                LoginActivity.editor.commit();

                connectToPush(); //MOVED TO HERE

            } else {
                Log.i("Server Token", "failed");
            }
        }
 }
Run Code Online (Sandbox Code Playgroud)

请随意删除我的问题。我会留下它,因为它可能会帮助别人