android 改造 - 如何进行顺序网络调用
retrofit for android - how to do sequential network calls
在我的 android 应用程序中,我有 3 个网络调用,它们依赖于它之前的调用。所以 1 必须完成,然后 2 可以继续,最后 3 得到 运行 和之前的数据。所以我需要按顺序对 运行 进行网络调用是目标。一次调用完成后,它会将数据传递给下一次调用等。我不想使用 rxJava。有没有办法通过改造来实现这一目标?我的项目已经在使用改造,因此我想继续使用它?我试过玩 asynchTask 但它不干净,因为我使用改造我想我会问。
如果您将 Retrofit 与异步 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. In the success
方法一起使用,则可以使用生成的接口的实例进行第二次网络调用,使用在 success
下返回的数据参数化类型 T
,以此类推用于第二个回调中的第三个调用。例如:
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));
这是一个使用异步调用链接的快速解决方案。在 AsyncTask
内部使用同步调用,这很可能看起来更顺序,更容易阅读,这将 return 类型直接 T
。例如:
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
}
}
在我的 android 应用程序中,我有 3 个网络调用,它们依赖于它之前的调用。所以 1 必须完成,然后 2 可以继续,最后 3 得到 运行 和之前的数据。所以我需要按顺序对 运行 进行网络调用是目标。一次调用完成后,它会将数据传递给下一次调用等。我不想使用 rxJava。有没有办法通过改造来实现这一目标?我的项目已经在使用改造,因此我想继续使用它?我试过玩 asynchTask 但它不干净,因为我使用改造我想我会问。
如果您将 Retrofit 与异步 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. In the success
方法一起使用,则可以使用生成的接口的实例进行第二次网络调用,使用在 success
下返回的数据参数化类型 T
,以此类推用于第二个回调中的第三个调用。例如:
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));
这是一个使用异步调用链接的快速解决方案。在 AsyncTask
内部使用同步调用,这很可能看起来更顺序,更容易阅读,这将 return 类型直接 T
。例如:
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
}
}