Create an Observer over a dynamic ArrayList

583 views
Skip to first unread message

Juan Pablo Vergara Villarraga

unread,
Mar 2, 2015, 1:22:17 PM3/2/15
to rxj...@googlegroups.com

I need to create an Observer over an array which is constantly changing (adding elements).

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.

I need the Observer to be notified and the Action to be executed everytime the ArrayList gets a new element added.


Dávid Karnok

unread,
Mar 2, 2015, 1:41:54 PM3/2/15
to rxj...@googlegroups.com
There are many ways of implementing this, depending on how much control do you have over the party that is adding to list. For example:

public class ObservableListExample {
    public static class ObservableList<T> {
        protected final List<T> list;
        protected final PublishSubject<T> onAdd;
        public ObservableList() {
            this.list = new ArrayList<>();
            this.onAdd = PublishSubject.create();
        }
        public void add(T value) {
            list.add(value);
            onAdd.onNext(value);
        }
        public Observable<T> addObservable() {
            return onAdd;
        }
    }
    
    public static void main(String[] args) {
        ObservableList<Integer> olist = new ObservableList<>();
        
        olist.addObservable().subscribe(System.out::println);
        
        olist.add(1);
        olist.add(2);
        olist.add(3);

Juan Pablo Vergara Villarraga

unread,
Mar 2, 2015, 2:20:44 PM3/2/15
to rxj...@googlegroups.com
Thank you so much Dávid. Since I´m new to RxJava I didn´t know the Subject classes. I was trying to do so using the basic creation methods for Observables.
Your example works pretty well.

Thanks again.
Reply all
Reply to author
Forward
0 new messages