RxJava2 .startWith(..)不起作用

时间:2018-01-23 13:27:57

标签: java rx-java reactive-programming

我有Observable发出一些String的内容:

List<String> list = // size this list is 5
Observable o1 = Observable.fromArray(list.toArray());

另一个每10秒钟发出一个物体:

Observable intervalObservable = Observable.interval(10, TimeUnit.SECONDS);

我想创建Observable,每隔10秒会发出o1中的每一项,所以我做了:

Observable change2tervalToString = intervalObservable.map(new Function() {
        @Override
        public Object apply(Object o) throws Exception {
            return "STARTER!";
        }
    });

Observable per10sec = o1.startWith(change2tervalToString);

如果我.subscribe()per10sec,它不会发出如下内容:

"STARTER", "ITEM_FROM_LIST1", "ITEM_FROM_LIST2", "ITEM_FROM_LIST3"...

但仅(每10秒钟):

"STARTER"

我想要达到这样的目标:

"STARTER", "ITEM_FROM_LIST1", "ITEM_FROM_LIST2", "ITEM_FROM_LIST3"...
....
....
 10 sec
....
....
"STARTER", "ITEM_FROM_LIST1", "ITEM_FROM_LIST2", "ITEM_FROM_LIST3"...
....
....
....

3 个答案:

答案 0 :(得分:3)

这个怎么样:

Observable.interval(10, TimeUnit.SECONDS).flatMap(new Function<Long, ObservableSource<String>>() {
            @Override
            public ObservableSource<String> apply(Long aLong) throws Exception {
                return Observable.fromIterable(list);
            }
        });

答案 1 :(得分:1)

为 rxjava3 尝试 startWithItem()

答案 2 :(得分:0)

让我们从另一方得出结论。

你想拥有:

"STARTER", "ListItem1", "ListItem2"...

这意味着:

Observable listItems = Observable.from(list.toArray());
Observable starter = Observable.just("STARTER");

Observable line = listItems.startWith(starter); // this will give you a line you want to emit

然后,你想每10秒发射一次。这意味着:

Observable timer = Observable.interval(10, TimeUnit.SECONDS);

// createLine() is the snippet from above.
Observable sequence = timer.flatMap(repetition -> createLine(list));

另外,假设你不想在收到第一个“行”之前等待10秒,你可能想要从一行开始:

sequence.startWith(createLine(list)); // first time emit immediately.

文档: