我在组合 BehaviorSubject
和 Observable.combineLatest
时遇到一些问题。我能够在(较小的)测试中重现它。这是当前失败的测试:
import org.junit.Test;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import io.reactivex.Observable;
import io.reactivex.observers.TestObserver;
import io.reactivex.subjects.BehaviorSubject;
import io.reactivex.subjects.Subject;
import static java.util.Collections.singletonList;
public class MyTest {
@Test
public void test() {
Subject<Integer> intSource = BehaviorSubject.createDefault(1);
Subject<List<Observable<Integer>>> mainSubject =
BehaviorSubject.createDefault(singletonList(intSource));
TestObserver<List<Integer>> testObserver =
mainSubject.flatMap(observables ->
Observable.combineLatest(observables, this::castObjectsToInts)
)
.test();
List<Observable<Integer>> newValue = new ArrayList<>();
newValue.add(intSource); // same value as before
newValue.add(Observable.just(2)); // add another value to this list.
mainSubject.onNext(newValue);
// intSource was already '1', but this is just to 'update' it.
intSource.onNext(1); // COMMENT OUT THIS LINE
testObserver.assertValueAt(0, singletonList(1));
testObserver.assertValueAt(1, Arrays.asList(1, 2));
testObserver.assertValueAt(2, Arrays.asList(1, 2)); // COMMENT OUT THIS LINE
testObserver.assertValueCount(3); // REPLACE 3 WITH 2
}
private List<Integer> castObjectsToInts(Object[] objects) {
List<Integer> ints = new ArrayList<>(objects.length);
for (Object object : objects) {
ints.add((Integer) object);
}
return ints;
}
}
(如果用“COMMENT OUT THIS LINE”注释掉这两行,并将最后一个 3
替换为 2
,则测试成功。)
为什么这个测试失败了?我没有发现代码有任何问题。
最佳答案
失败是因为您忘记了 mainSubject.flatMap
仍然有第一个 intSource
处于 Activity 状态,因此 intSource.onNext(1)
将首先触发 combineLatest
序列。 testObserver.assertValueAt(2)
将成为 List
中的单个值。 assertValueAt(3)
将包含 1, 2
,整个序列有 4 个项目。
关于java - RxJava 2 : BehaviorSubject and Observable. 合并最新问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48140316/