简体   繁体   中英

RxJava 2: How to filter items of infinite stream that emits “List<Item>”?

I have an Observable that does never finish. It emits a List<Item> . I need to filter out some of those items every time it emits that list. Currently I have this as a solution:

mData.getItemsObservable() // Observable<List<Item>>
        .compose(...)
        .flatMapSingle(items -> Observable.fromIterable(items)
                .filter(item -> item.someCondition())
                .toList())
        .subscribe(items -> {
            // ...
        }, error -> {
            // ...
        });

Is this the best way to filter out some items? Is there a simpler (more readable) way to do the same?

I've tried this too, but it didn't emit anything:

mData.getItemsObservable() // Observable<List<Item>>
        .compose(...)
        .flatMap(Observable::fromIterable) // or like this: flatMapIterable(items -> items)
        .filter(item -> item.someCondition())
        .toList()
        .subscribe(items -> {
            // ...
        }, error -> {
            // ...
        });

The first approach is okay if you want to stick to RxJava . Otherwise, you could use IxJava and perform the filtering directly in a map operation:

mData.getItemsObservable() // Observable<List<Item>>
    .compose(...)
    .map(v -> Ix.from(v).filter(w -> w.someCondition()).toList())
    .subscribe(items -> {
        // ...
    }, error -> {
        // ...
    });

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