Advertisement
NLinker

Dynamic observable list

Apr 11th, 2016
191
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.15 KB | None | 0 0
  1. import java.util.ArrayList;
  2. import java.util.List;
  3. import java.util.ListIterator;
  4.  
  5. import rx.Observable;
  6. import rx.subjects.PublishSubject;
  7.  
  8. /**
  9.  * http://stackoverflow.com/questions/28816691/how-can-i-create-an-observer-over-a-dynamic-list-in-rxjava
  10.  */
  11. public class ObservableRxList<T> {
  12.  
  13.     protected final List<T> list;
  14.     protected final PublishSubject<T> subject;
  15.  
  16.     public ObservableRxList() {
  17.         this.list = new ArrayList<T>();
  18.         this.subject = PublishSubject.create();
  19.     }
  20.  
  21.     public void add(T value) {
  22.         list.add(value);
  23.         subject.onNext(value);
  24.     }
  25.  
  26.     public void update(T value) {
  27.         for (ListIterator<T> it = list.listIterator(); it.hasNext(); ) {
  28.             if (value.equals(it.next())) {
  29.                 it.set(value);
  30.                 subject.onNext(value);
  31.                 return;
  32.             }
  33.         }
  34.     }
  35.  
  36.     public void remove(T value) {
  37.         list.remove(value);
  38.         subject.onNext(value);
  39.     }
  40.  
  41.     public Observable<T> getObservable() {
  42.         return subject;
  43.     }
  44.  
  45.     public Observable<T> getCurrentList() {
  46.         return Observable.from(list);
  47.     }
  48.  
  49. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement