我在 3 个线程中的每一个线程中都有多个 API 调用。但是,当通过这些 API 调用发送大量数据时,应用程序运行速度会变慢,有时甚至会导致 API 响应失败。如果可能,是否有更好的方法来执行此任务或按顺序运行这些线程。
我也尝试使用异步任务,但没有像预期的那样处理大量数据。
Thread thread1 = new Thread(new Runnable() {
@Override
public void run() {
//First Retrofit API calls
//Second Retrofit API calls
}
});
Thread thread2 = new Thread(new Runnable() {
@Override
public void run() {
//Third Retrofit API call
//Fourth Retrofit API call
}
});
Thread thread3 = new Thread(new Runnable() {
@Override
public void run() {
//Fifth Retrofit API call
//Sixth Retrofit API call
}
});
thread1.start();
thread2.start();
thread3.start();
- 在 app:gradle 中添加 RxJava
android {
...
}
dependencies {
...
implementation 'io.reactivex.rxjava2:rxjava:2.2.6'
implementation 'io.reactivex.rxjava2:rxandroid:2.1.1'
...
}
使用 RxJava 包装每个 api 调用或使用 Retrofit 进行 api 调用。
使用 Observable.Zip 函数:
Observable.zip(
/*first api call observable*/,
/*second api call observable etc*/,
BiFunction<
/*first api call response*/,
/*second api call response*/,
/*result of function below*/> { result_of_first_call, result_of_second_call ->
//do something with result
}).subscribe {
//update your UI, etc
}
请参阅:https://medium.com/@nicolas.duponchel/rx-java-for-beginners-8b7c1e7bfc44