简体   繁体   English

Android的改造-如何进行顺序网络调用

[英]retrofit for android - how to do sequential network calls

in my android app i have 3 network calls and they are dependent on the call before it. 在我的android应用程序中,我有3个网络呼叫,它们取决于之前的呼叫。 So 1 must finish, then 2 can go and finally 3 gets run with the data from the previous ones. 因此,必须完成1项,然后2项才能完成,最后3项将使用来自先前数据的数据运行。 So i need the network calls to run sequentially is the goal. 因此,我需要网络电话按顺序运行是目标。 after one call is finished it will have data passed to the next call, etc. I dont want to use rxJava. 一个调用完成后,它将有数据传递给下一个调用,等等。我不想使用rxJava。 Is there a way with retrofit to make this happen ? 有没有办法进行改造以实现这一目标? My project is already using retrofit thus i want to continue using it ? 我的项目已经在使用改造,因此我要继续使用吗? I've tried playing around with asynchTask but its not clean and since im using retrofit i thought i would ask. 我试过与asynchTask玩耍,但它不干净,而且自从我使用改造后,我想我会问。

If you're using Retrofit with the asynchronous Callback s then for the first network call you can pass in the generated interface which represents the web service that you're interacting with. 如果您将Retrofit与异步Callback一起使用,则对于第一个网络呼叫,您可以传递生成的接口,该接口表示您正在与之交互的Web服务。 In the success method you can then use the instance of the generated interface to make a second network call, using the data which came back in success under the parametrised type T , and so on for the third call inside a second callback. 然后,在success方法中,您可以使用生成的接口的实例进行第二次网络调用,使用在参数化类型Tsuccess返回的数据,以此类推,在第二个回调中进行第三次调用。 For example: 例如:

class FirstCallback implements Callback<First> {

  private Api api;

  public FirstCallback(Api api) {
    this.api = api;
  }

  void success(First data, Response response) {
    api.secondCall(data, new SecondCallback(api))
  }
}

// somewhere else in your code
api.firstCall(new FirstCallback(api));

This is a quick solution using chaining with the asynchronous calls. 这是将链接与异步调用结合使用的快速解决方案。 This would most likely look more sequential and easier to read inside of an AsyncTask using the synchronous calls, which would return the type T directly. 这很可能看起来更具顺序性,并且使用同步调用可以更轻松地在AsyncTask读取,这将直接返回类型T For example: 例如:

class MyTask extends AsyncTask<Void, Void, Void> {

  protected Void doInBackground(Void... params) {
    First first = api.firstCall();
    Second second = api.secondCall(first);
    // ...and so on until you return the final result
  }
}

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

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