简体   繁体   English

带foreach循环的RxJava Retrofit请求链

[英]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. 我的目标是执行以下操作。

  1. Send ModelGroup to the server and receive a response, which is an integer, representing the newly inserted ID, let's call it newGroupId. 将ModelGroup发送到服务器并接收响应,该响应是一个整数,代表新插入的ID,我们将其称为newGroupId。
  2. For each ModelPerson in ModelGroup, set Person.groupId to newGroupId. 对于ModelGroup中的每个ModelPerson,将Person.groupId设置为newGroupId。
  3. Send each person to the server. 将每个人发送到服务器。
  4. If all ModelPerson objects from the ModelGroup were successfully updated with newGroupId then respond with onSuccess, otherwise onError. 如果使用newGroupId成功更新了ModelGroup中的所有ModelPerson对象,则使用onSuccess响应,否则使用onError响应。

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.

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