observables
和观察者在RxJava
中的正确概念和工作原理是什么?我被字面意思弄糊涂了。每当我更改observables
的值时,它的相应观察者就不会被调用--我将更深入地解释这种情况,最初,当我为一个observable
分配一个字符串列表(列表)并将其订阅给一个观察者时,观察者工作得很好,但在那之后,当我更改list的值(例如向list中添加更多的字符串值)时,...the观察者的next应该自动被正确地调用。但事实并非如此,试图在安卓系统中实现。我会很高兴得到一些帮助的。
发布于 2018-04-27 05:35:01
Observables
使用来自Observer
的三种方法:onNext
、onError
和onCompleted
。当您从列表中创建Observable
并订阅它时,可观察到的将使用onNext
方法发出这些值,当它完成时,它将调用onCompleted
方法。
你不能通过改变你给一些可观测运算符的列表来改变那些可以观察到的值。你想要什么行为。是Observable
发出列表更改中的所有元素,还是只发出新的更改。
此可观察到的setCollection
方法将发出对集合的所有更改:
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);
}
}
}
}
注意,要完成手动操作,必须调用complete
方法。
https://stackoverflow.com/questions/50061933
复制相似问题