我有以下Rx链:
compositeDisposable.add(manager.getObservable()
.map(objects -> modelMapper.map(objects))
.map(modelObjects -> {
cache.save(modelObjects);
return modelObjects ;
})
.flatMapIterable(modelObjects -> modelObjects)
.sorted(objectComparator)
.toList()
.map(modelObjects -> viewModelMapper.map(modelObjects))
.subscribe(this::onObjectsLoaded));
我想将运算符flatMapIterable(modelObjects -> modelObjects)
,sorted(objectComparator)
和toList()
提取到一个单独的方法中,我可以在多个Rx链中重复使用它来对对象进行排序,因此链看起来像这个:
compositeDisposable.add(manager.getObservable()
.map(objects -> modelMapper.map(objects))
.map(modelObjects -> {
cache.save(modelObjects );
return modelObjects ;
})
.compose(sortObjects())
.map(modelObjects -> viewModelMapper.map(modelObjects))
.subscribe(this::onObjectsLoaded));
是否可以创建这样的方法? 谢谢!
答案 0 :(得分:3)
定义一个采用Observable
并返回Observable
的方法:
static <T> Observable<List<T>> sortListItem(Observable<List<T>> source,
Comparator<? super T> comparator) {
return source.flatMapIterable(v -> v)
.toSortedList(comparator)
.toObservable();
}
compositeDisposable.add(manager.getObservable()
.map(objects -> modelMapper.map(objects))
.map(modelObjects -> {
cache.save(modelObjects);
return modelObjects ;
})
.compose(ThisClass::sortListItem)
.map(modelObjects -> viewModelMapper.map(modelObjects))
.subscribe(this::onObjectsLoaded));