Skip to content

Instantly share code, notes, and snippets.

@mauricegavin
Created February 29, 2016 18:15
Show Gist options
  • Save mauricegavin/fae0081c056327958ef4 to your computer and use it in GitHub Desktop.
Save mauricegavin/fae0081c056327958ef4 to your computer and use it in GitHub Desktop.
ObservableRxList
import java.util.ArrayList;
import java.util.List;
import java.util.ListIterator;
import rx.Observable;
import rx.subjects.PublishSubject;
/**
* http://stackoverflow.com/questions/28816691/how-can-i-create-an-observer-over-a-dynamic-list-in-rxjava
*/
public class ObservableRxList<T> {
protected final List<T> list;
protected final PublishSubject<T> subject;
public ObservableRxList() {
this.list = new ArrayList<T>();
this.subject = PublishSubject.create();
}
public void add(T value) {
list.add(value);
subject.onNext(value);
}
public void update(T value) {
for (ListIterator<T> it = list.listIterator(); it.hasNext(); ) {
if (value.equals(it.next())) {
it.set(value);
subject.onNext(value);
return;
}
}
}
public void remove(T value) {
list.remove(value);
subject.onNext(value);
}
public Observable<T> getObservable() {
return subject;
}
public Observable<T> getCurrentList() {
return Observable.from(list);
}
}
@jam01
Copy link

jam01 commented Jun 11, 2016

The subject subscriber would not know when the operation was an addition, removal. etc... Or am I missing something?

@kibotu
Copy link

kibotu commented Aug 18, 2016

if (value.equals(it.next())) {

would always fail though. didn't you try to compare references to update here? otherwise try to updateAt instead

@erfanegtfi
Copy link

erfanegtfi commented Apr 16, 2020

Hi, @jam01 is right, I improved your answer and post here

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment