RxJava 2 Nested Network Requests

我与影子孤独终老i 提交于 2019-12-11 14:58:44

问题


in the app I am currently working on I use retrofit to create an Observable <ArrayList<Party>>.

Party has a hostId field as well as a field of type User which is null at the point of creation by Retrofits GsonConverter. I now want to use hostId to make a second request getting the user from id and adding the User to the initial Party. I have been looking into flatmap but I haven't found an example in which the first observable's results are not only kept but also modified.

Currently, to get all parties without the User I am doing :

Observable<ArrayList<Party>> partiesObs = model.getParties();

partiesObs.subscribeOn(Schedulers.io())
        .observeOn(AndroidSchedulers.mainThread())
        .subscribe(this::handlePartyResponse, this::handleError);

How would I go about adding User to every Party without having to call model.getUsers() in the onSuccess() method of the inital call and then having to iterate through the two lists?

I understand that flatmap() returns a new Observable while map doesn't but I am unsure about how to use either in this scenario.

Thank you


回答1:


As in the comment, you should try and get the backend API changed for something like this to avoid an inelegant and inefficient solution.

If this is not feasible, you could probably do something like this:

    .flatMapIterable(list -> list)
    .flatMap(party -> model.getUser(party.hostId),
            (party, user) -> new Party(user, party.hostId, party.dontCare))

Where:

  1. flatMapIterable flattens the Observable<ArrayList<Party>> into an Observable<Party>
  2. The overload of flatMap takes a Function for transforming emissions (Party objects) into an ObservableSource (of User objects) as the first parameter. The second parameter is a BiFunction for combining the Party and User objects which you can use to create a fully fledged Party object.

The last step is much easier if you have a copy or clone operation on the Party object that takes a previous instance and adds fields to it.



来源:https://stackoverflow.com/questions/49210682/rxjava-2-nested-network-requests

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!