简体   繁体   中英

RxJava2 - Reuse operator sequence for multiple Rx chains

I have the following Rx chain:

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));

I want to extract the operators flatMapIterable(modelObjects -> modelObjects) , sorted(objectComparator) and toList() into a separate method that I can reuse in multiple Rx chains to sort the objects, so the chain will look something like this:

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));

Is is possible to create such a method? Thanks!

Define a method that takes an Observable and returns an 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));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM