问题
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:
flatMapIterable
flattens theObservable<ArrayList<Party>>
into anObservable<Party>
- The overload of flatMap takes a
Function
for transforming emissions (Party
objects) into anObservableSource
(ofUser
objects) as the first parameter. The second parameter is aBiFunction
for combining theParty
andUser
objects which you can use to create a fully fledgedParty
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