我想将divider对象插入到集合中。
Observable<String> observable = Observable.from(new String[] { "a", "b", "c" });
Iterable<String> dividedList = observable.flatMapIterable(new Func1<String, Iterable<String>>() {
@Override public Iterable<String> call(String s) {
return Lists.newArrayList(s, "divider");
}
}).toBlocking().toIterable();
我想要["a", "divider", "b", "divider", "c"]
,
但实际上,当然是["a", "divider", "b", "divider", "c", "divider"]
如何使用RxJava执行此操作?
答案 0 :(得分:4)
使用skipLast
运算符删除最后一个元素!
Observable.just("a", "b", "c")
.flatMap((l) -> Observable.just(l, "divider"))
.skipLast(1)
.toBlocking().toIterable();
答案 1 :(得分:3)
您可以反转这些对,以便[sep,element]删除第一个项目。
public static <T> Iterable<T> interpose(T sep, T[] seq) {
return Observable.from(seq)
.flatMap(s -> Observable.just(sep, s))
.skip(1).toBlocking().toIterable();
}
public static void main(String[] args) {
Iterable<String> dividedList = interpose("|", new String[] { "a", "b", "c", "d" });
dividedList.forEach(s -> System.out.print(s.toString()+" "));
System.out.println();
}
a | b | c | d