簡體   English   中英

Retrofit 異步條件調用

[英]Retrofit Asynchronous call on condition

我必須從 API 接收令牌,將其存儲在共享首選項中,僅令牌過期時才調用 API。 令牌在 200000 秒后過期。 基本上我會嘗試按照以下說明進行操作:

  1. 生成令牌並將其存儲在 session
  2. 存儲您生成令牌的時間,也就是當前時間
  3. 每當您撥打 API 電話時,根據當前時間檢查令牌過期時間
  4. 如果令牌過期時間大於當前時間,則重新驗證並在后台生成新令牌

但是,甚至在生成令牌之前就進行了第一個 API 調用,並將 null 作為令牌傳遞,然后生成令牌並將其存儲在共享首選項中。 所以它只是第一次不起作用,然后才起作用。 使用 if 條件和異步 Retrofit 調用是否有問題。

這是我用來創建令牌的 function

public void getToken(){
    Credentials credentials=new Credentials("public_user","public_pass");

    Call<Authentication> call=service.getToken(credentials);
    call.enqueue(new Callback<Authentication>() {
        @RequiresApi(api = Build.VERSION_CODES.O)
        @Override
        public void onResponse(Call<Authentication> call, Response<Authentication> response) {

            if (response.body().getCode() != 0) {

                 token = response.body().getDocument();

                SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(ctx.getApplicationContext());
                SharedPreferences.Editor editor=preferences.edit();
                editor.putString("token",token).commit();
                tokenExpires=Instant.now().plus(Duration.ofSeconds(200000));
                long millis=tokenExpires.toEpochMilli();
                editor.putLong("token_expiry_time",millis).commit();
                String this_token=preferences.getString("token",null);

            }
        }

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

        }
    });
}

這就是我如何調用這個 function 並使用它來調用 API

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    
     service = ApiClient.getClientStats().create(ApiInterface.class);
    SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(ctx.getApplicationContext());
    String retrievedToken  = preferences.getString("token",null);
    long token_expiry_time=preferences.getLong("token_expiry_time",0);

    if(retrievedToken==null || token_expiry_time==0 || token_expiry_time<=Instant.now().toEpochMilli()) {
        getToken();
        retrievedToken=token;
    }

    else {


        Call<Stat> call = service.getMapData("Bearer " + retrievedToken);
        call.enqueue(new Callback<Stat>() {
            @Override
            public void onResponse(Call<Stat> call, Response<Stat> response) {

                


                }
            }

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

            }
        });
    }

當您調用 getToken() 時,retrofit 在另一個線程上運行它。 當發生這種情況時,主線程繼續在 if 語句中執行並將 null 分配給 retrieveToken,因為當時令牌是 null,這就是為什么您擁有第一個 null 的原因。然后 retrofit 完成它的執行並設置共享首選項。 您可以在進行其他查詢之前使用LiveData觀察結果。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM