RxJava:插入分隔器对象

RxJava:插入分隔器对象,java,rx-java,Java,Rx Java,我想在集合中插入分隔器对象 Observable<String> observable = Observable.from(new String[] { "a", "b", "c" }); Iterable<String> dividedList = observable.flatMapIterable(new Func1<String, Iterable<String>>() { @Override public Iterable<S

我想在集合中插入分隔器对象

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();
Observable-Observable=Observable.from(新字符串[]{“a”、“b”、“c”});
Iterable dividedList=可观察的.flatMapIterable(新Func1(){
@重写公共Iterable调用(字符串s){
返回列表。newArrayList(“分隔符”);
}
}).toBlocking().toIterable();
我想要
[“a”,“divider”,“b”,“divider”,“c”]
, 但实际上,当然是
[“a”,“divider”,“b”,“divider”,“c”,“divider”]


如何使用RxJava实现这一点?

只需使用
skipLast
操作符删除最后一个元素

Observable.just("a", "b", "c")
          .flatMap((l) -> Observable.just(l, "divider"))
          .skipLast(1)
          .toBlocking().toIterable();

只需使用
skipLast
操作符删除最后一个元素

Observable.just("a", "b", "c")
          .flatMap((l) -> Observable.just(l, "divider"))
          .skipLast(1)
          .toBlocking().toIterable();

您可以反转这些对,以使[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();
}
公共静态可写插入(T sep,T[]seq){
可观察的回报率。来源(seq)
.flatMap(s->Observable.just(sep,s))
.skip(1).toBlocking().toIterable();
}
公共静态void main(字符串[]args){
Iterable dividedList=插入(“|”),新字符串[]{“a”、“b”、“c”、“d”});
dividedList.forEach(s->System.out.print(s.toString()+);
System.out.println();
}
a | b | c | d


您可以反转这些对,以使[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();
}
公共静态可写插入(T sep,T[]seq){
可观察的回报率。来源(seq)
.flatMap(s->Observable.just(sep,s))
.skip(1).toBlocking().toIterable();
}
公共静态void main(字符串[]args){
Iterable dividedList=插入(“|”),新字符串[]{“a”、“b”、“c”、“d”});
dividedList.forEach(s->System.out.print(s.toString()+);
System.out.println();
}
a | b | c | d


我只知道
skip(1)
skipLast(1)
的实用用法,谢谢!您可能希望在此处使用
concatMap
而不是
flatMap
,以确保订单得以保留。我只知道
skip(1)
skipLast(1)
的实用用法,谢谢!您可能希望在此处使用
concatMap
,而不是
flatMap
,以确保保留订单。