如何通过 RxJava 中的动态列表创建观察者? [英] How can I create an Observer over a dynamic list in RxJava?
本文介绍了如何通过 RxJava 中的动态列表创建观察者?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要在一个不断变化(添加元素)的数组上创建一个观察者.
I need to create an Observer over an array which is constantly changing (adding elements).
我正在使用 Obserable.from(Iterable) 但它似乎在 ArrayList 上创建了 Observable,就像创建时一样.
I am using Obserable.from(Iterable) but it seems that it creates the Observable over the ArrayList as it is at the moment of the creation.
我需要在每次 ArrayList 添加新元素时通知观察者并执行操作.
I need the Observer to be notified and the Action to be executed everytime the ArrayList gets a new element added.
推荐答案
你去吧.感谢 RxJava Google Group 上的 Dávid Karnok
There you go. Thanks to Dávid Karnok on RxJava Google Group
import java.util.ArrayList;
import java.util.List;
import rx.Observable;
import rx.subjects.PublishSubject;
public class ObservableListExample {
public static class ObservableList<T> {
protected final List<T> list;
protected final PublishSubject<T> onAdd;
public ObservableList() {
this.list = new ArrayList<T>();
this.onAdd = PublishSubject.create();
}
public void add(T value) {
list.add(value);
onAdd.onNext(value);
}
public Observable<T> getObservable() {
return onAdd;
}
}
public static void main(String[] args) throws Exception {
ObservableList<Integer> olist = new ObservableList<>();
olist.getObservable().subscribe(System.out::println);
olist.add(1);
Thread.sleep(1000);
olist.add(2);
Thread.sleep(1000);
olist.add(3);
}
}
这篇关于如何通过 RxJava 中的动态列表创建观察者?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文