我有以下方法,其中我使用RxJava从Api获取一些数据,然后操纵该数据以获取用户名列表和用户列表。
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);
}
我不喜欢 doOnNext 中的这种方法,因为我认为它可以改进,但不确定如何做。
有人可以写出更好的解决方案吗?
答案 0 :(得分:1)
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);
编辑:这与原始剪辑的功能不同;我相信以下内容:
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));
}