[英]RxJava Retrofit chain of requests with foreach loop
I'm trying to migrate from using plain Retrofit to using the RxJava extension for retrofit in order to make chain of API calls on the background thread. 我试图从使用普通Retrofit迁移到使用RxJava扩展进行改造,以便在后台线程上进行API调用链。
For example, I have an object called ModelGroup which has a list of ModelPerson objects. 例如,我有一个名为ModelGroup的对象,该对象有一个ModelPerson对象列表。 My goal is to do the following.
我的目标是执行以下操作。
My current solution can be seen below. 我当前的解决方案如下所示。
private void makeGroupInsert(ModelGroup modelGroup) {
int newGroupId = myApi.insertNewGroup(modelGroup.getName(), modelGroup.getRating())
.execute()
.body();
for (ModelPerson person : modelGroup.getPersons()) {
person.setGroupId(newGroupId);
String response = myApi.insertNewPerson(
person.getGroup_id(),
person.getFirst_Name(),
person.getLast_Name())
.execute()
.body();
if (!response.equals("success")) {
// One failed to update, send error to main thread.
}
}
// All succeeded, send success back to main thread.
}
Question 题
How can I achieve the same (or better) functionality using a RxJava + Retrofit solution? 如何使用RxJava + Retrofit解决方案实现相同(或更好)的功能?
EDIT 1 编辑1
MyApi is defined below. MyApi在下面定义。
public interface MyApi {
@POST("insert_new_group")
Call<Integer> insertNewGroup(@Query("group_name") String groupName,
@Query("group_rating") int rating);
@POST("insert_new_person")
Call<String> insertNewPerson(@Query("group_id") int groupId,
@Query("first_name") String firstName,
@Query("last_name") String lastName);
}
First of all, you need to change Retrofit beans to use Observables. 首先,您需要将Retrofit bean更改为使用Observables。 For example, it can look like the following line:
例如,它看起来像下面的行:
@POST("insert_new_group")
Observable<Integer> insertNewGroup(...
Then you can chain requests: 然后,您可以链接请求:
void updateData() {
myApi.insertNewGroup(modelGroup.getName(), modelGroup.getRating()) //Creating new group and getting its ID
.switchMap(this::setGroupIdAll) //Calling observable that will loop thru all persons and set their groupIDs
.subscribe(
(n) -> {/*you will get String after every 'insertNewPerson' run*/},
(e) -> {/*error handling*/}
);
}
Observable<String> setGroupIdAll(Integer id) {
return Observable.fromIterable(personsIterable) //personsIterable contains all your ModelPerson objects
.flatMap(this::updatePerson); //Call Observabl;e that will send updated person to the server
}
Observable<String> updatePerson(ModelPerson person) {
return myApi.insertNewPerson(
person.getGroup_id(),
person.getFirst_Name(),
person.getLast_Name());
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.