android - 如何知道 Retrofit 调用何时完成

标签 android web-services api retrofit retrofit2

有没有办法知道我的 Retrofit 调用何时完成它的职责?我想知道何时收到所有数据以便代码可以继续,例如开始另一个 Activity 或使用第一次调用的数据进行第二次调用?

Ps.: 我使用的是异步请求(.enqueue)。

编辑:

getContact(){ 
//Get a contact List from the server    
    Call<List<ModelContact>> callM =  contactInterface.createRContact(listContact);
    callM.enqueue(new Callback<List<ModelContact>>() {
    @Override

    public void onResponse(Response<List<ModelContact>> response, Retrofit retrofit) {
        // Fetch the List from Response and save it on the local database
        }

    @Override
        public void onFailure(Throwable t) {
            Log.i("TAG", "Error: " + t.getMessage());
        }
    });

    //Gets a object containing some configurations
    Call<Configs> callC = contactInterface.getConfigs(Configs);
    callC.enqueue(new Callback<Configs>() {
    @Override

    public void onResponse(Response<Configs> response, Retrofit retrofit) {
        // Fetch the Configs object and save it on the database
        }

    @Override
        public void onFailure(Throwable t) {
            Log.i("TAG", "Error: " + t.getMessage());
        }
    });

    //Here I need to start a new activity after the calls
    Intent loginact = new Intent(TokenActivity.this, LoginActivity.class);
           startActivity(loginact);


}

最佳答案

也许您可以使用两个 bool 标志并在 getContact 方法之外启动新 Intent 。

是这样的:

public class MyActivity extends Activity {
    //lot of code omitted 
    private boolean cIsFinished;
    private boolean mIsFinished;

    private void getContact(){
      //create M and C 
      m.onResponse(){
        //do whatever you want with data and call startIntent
        mIsFinished=true;
        startIntent();
      }
      c.onResponse(){
        //do whatever you want with data and call startIntent
        cIsFinished=true;
        startIntent();
      }


    }
    private synchronized void startIntent(){
       if(cIsFinished && mIsFinished){
          //startIntentHere!
          Intent intent = new blah blah blah
       }

    }    
}

关于android - 如何知道 Retrofit 调用何时完成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34752710/

相关文章:

java - 如何在 java 中创建将输入作为 JSONObject 的简单 Web 服务

php - 如何使用 PHP 计算目录中的文件数量?

用于 spring-mvc rest api 文档的类似 javadoc 的工具?

php - WooCommerce REST API - 在没有太多请求的情况下获取所有有变化的产品

java - Android 应用程序中的 Google 翻译 API

java - Date() 的使用;不给出当前日期

android - 如何保存完整的网页并稍后加载以供离线访问

android - 如果应用未处于 Activity 状态,Vibrator.vibrate() 在 Android 10 Pie 中不执行任何操作

c# - 将服务引用添加到 ASP.NET 应用程序

javascript - 如何在 while 循环内异步发出后续 http 请求而不使用 Promise 和 async/await?