Reputation: 2707
I have the following method where I use RxJava to get some data from Api and then I manipulate that data to get list of user names and list of users.
public void getUsers(){
disposables = RxUtil.initDisposables(disposables);
Disposable disposable = userApiRepository.getUsers()
.subscribeOn(Schedulers.io())
.doOnNext(otherUsers -> {
List<String> names = new ArrayList<>();
for(OtherUser otherUser: otherUsers){
names.add(otherUser.getDisplayName());
}
String[] userNames = names.toArray(new String[names.size()]);
view.onUserNamesLoaded(userNames);
})
.observeOn(AndroidSchedulers.mainThread())
.subscribe(otherUsers -> view.onUsersLoaded(otherUsers),
view::handleError);
disposables.add(disposable);
}
I do not like this approach in doOnNext, since I think that it could be improved, but not sure how.
Can someone write a better solution?
Upvotes: 0
Views: 110
Reputation: 16152
userApiRepository
.getUsers()
.subscribeOn(Schedulers.io())
.flatMapIterable(users -> users)
.map(OtherUser::getDisplayName)
.toList()
.doOnNext(names -> view.onUserNamesLoaded(names.toArray(new String[names.size()])))
.observeOn(AndroidSchedulers.mainThread())
.subscribe(otherUsers -> view.onUsersLoaded(otherUsers),
view::handleError);
Edit: this doesn't do what the original snipped did; I believe the following does:
userApiRepository
.getUsers()
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.doOnNext(otherUsers -> updateViewWithUserNames(otherUsers, view))
.subscribe(otherUsers -> view.onUsersLoaded(otherUsers),
view::handleError);
private void updateViewWithUserNames(List<OtherUsers> otherUsers, View view) {
view.onUserNamesLoaded(otherUsers.stream()
.map(OtherUser::getDisplayName)
.toArray(String[]::new));
}
Upvotes: 1