2015-03-19 45 views
1

我想插入分隔符對象到集合中。RxJava:插入分隔符對象

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做到這一點?

回答

4

只需使用skipLast運算符刪除最後一個元素即可!

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

我剛剛纔知道'skip(1)'或'skipLast(1)'的實用用法,謝謝! – 2015-03-20 01:48:31

+1

你可能想在這裏使用'concatMap'而不是'flatMap'來保證排序被保留。 – lopar 2015-03-21 01:38:28

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