Reputation: 1
What are the correct concepts and working of observables
and observers in RxJava
. I get confused by the words literal meaning. Whenever I change the values of observables
its corresponding observers is not getting invoked i.e. I will explain this situation a bit more deeply, initially when I assign an observable
with a list of strings(List list) and subscribe it to an observer, observer works perfectly but after that ,when I change the values of list(for example adding more String values to list) ...the observer's on next should automatically be invoked right.. but it isn't. Trying to implement in Android natively . I will be happy for some helps.
Upvotes: 0
Views: 45
Reputation: 1153
Observables
work with three methods from Observer
: onNext
, onError
and onCompleted
. When you make Observable
from a list and you subscribe it Observable will emit those values using onNext
method and when it's finished it will call onCompleted
method.
You can't change values that Observable is emitting by changing list you gave to some Observable operator. What would be you desired behaviour. Should Observable
emit all elements on list change or should it emit only new changes.
This observable will emit all changes to collection made trough setCollection
method:
public class CollectionObservable<T> extends Observable<T> {
private Collection<T> collection;
private List<Observer<? super T>> observers;
public CollectionObservable(Collection<T> collection) {
if (collection != null) {
this.collection = collection;
}
this.observers = new ArrayList<>(2);
}
public Collection<T> getCollection() {
return collection;
}
public void setCollection(Collection<T> collection) {
this.collection = collection;
emitValuesToAllObserver();
}
public void complete() {
if (this.collection != null) {
for (Observer<? super T> observer : this.observers) {
observer.onComplete();
}
}
}
@Override
protected void subscribeActual(Observer<? super T> observer) {
this.observers.add(observer);
emitValues(observer);
}
private void emitValuesToAllObserver() {
for (Observer<? super T> observer : this.observers) {
emitValues(observer);
}
}
private void emitValues(Observer<? super T> observer) {
if (this.collection != null) {
for (T obj : this.collection) {
observer.onNext(obj);
}
}
}
}
Note that in order to finish you manually have to call complete
method.
Upvotes: 1