用RX Java或首先获取过滤器索引的绝佳方法 [英] Elegant way to get index of filter or first with RX Java
本文介绍了用RX Java或首先获取过滤器索引的绝佳方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我只是在练习RX Java,想获取数组中与过滤器匹配的项的位置.我看不到任何明显的方法.我当时在寻找压缩范围和可迭代的可观察范围之类的东西,但是它很快变得比for循环更冗长和复杂.
I'm just practicing RX Java and wanted to get the position in an array for items which match a filter. I can't see any obvious way to do it. I was looking at maybe zipping a range and iterable observable or something but it was quickly getting way more verbose and complicated than for loops.
推荐答案
RxJava中曾经有mapWithIndex
和zipWithIndex
运算符,但是它们已被删除,请参见
There used to be mapWithIndex
and zipWithIndex
operators in RxJava, but they were removed, see here why.
因此,您必须编写一些库样板:
So you have to write some library boilerplate once:
class Indexed<T> {
final int index;
final T value;
public Indexed(T value, int index) {
this.index = index;
this.value = value;
}
@Override
public String toString() {
return index + ") " + value;
}
}
Iterable<Integer> naturals = IntStream.iterate(0, i -> i + 1)::iterator;
但是随后,您可以使其简洁明了:
But then, you can get it reasonably concise:
Observable<String> obs = Observable.just("zero", "one", "two", "three");
obs.zipWith(naturals, (s, i) -> new Indexed<String>(s, i))
.filter(e -> e.value.length() > 4)
.subscribe(System.out::println);
这篇关于用RX Java或首先获取过滤器索引的绝佳方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文