什么是正确的概念和工作observables和观察者RxJava。我对字面意思感到困惑。每当我更改observables其相应观察者的值时,都不会被调用,即我将更深入地解释这种情况,最初当我分配一个observable字符串列表(列表列表)并将其订阅给观察者时,观察者工作完美但之后那,当我更改列表的值时(例如向列表添加更多的字符串值)......接下来的观察者应该被自动调用......但事实并非如此。尝试在Android 中原生实现。我会很高兴得到一些帮助。
1 回答
1
ObservablesObserver使用来自:onNext和onError的三种方法onCompleted。当您Observable从列表中创建并订阅它时,Observable 将使用onNext方法发出这些值,完成后它将调用onCompleted方法。
您不能通过更改您提供给某些 Observable 运算符的列表来更改 Observable 发出的值。你想要什么行为。应该Observable在列表更改时发出所有元素,或者它应该只发出新的更改。
setCollection此 observable 将发出对通过槽方法进行的收集的所有更改:
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方法。
于 2018-04-27T13:35:01.943 回答