我想将两个可观察变量names
和nums
组合成一个Student
类-一种反映这些可观察变量的最新状态的模式。
这两个可观察物都在发射,并且onNext
始终打印为nums
和names
。
但是,只有将combineLatest emits
观察对象放在第一位,观察对象才从nums
返回。
public class RxTrial1 {
public static class Student{
public String name;
public long roll;
public Student(String name, long roll) {
super();
this.name = name;
this.roll = roll;
}
@Override
public String toString() {
return "Student [" + (name != null ? "name=" + name + ", " : "") + "roll=" + roll + "]";
}
}
public static void main(String[] args) {
Observable<String> strs = Observable.just("a", "b", "c").repeat();
ConnectableObservable<Long> nums = Observable.interval(1, TimeUnit.SECONDS)
.doOnNext( n -> System.out.println( "nums: " + n ) )
.publish();
Observable<String> names = nums
.zipWith(strs, (n, s)->{ return s+n; })
.doOnNext( s -> System.out.println( "names: " + s ) );
Observable.combineLatest(nums, names, (s, n)->{ return new Student(n,s); })
.subscribeOn(Schedulers.newThread())
.doOnNext( st -> System.out.println( "combined: " + st ) )
.subscribe( st -> System.out.println( "Student: " + st ) );
nums.connect();
wait10();
}
private static void wait10() {
System.out.println("Start waiting");
try {
Thread.sleep(10_000l);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Done waiting");
}
}
为什么仅将nums
放在第一位会发光?
首先与nums
配合良好:
Start waiting
nums: 0
names: a0
combined: Student [name=a0, roll=0]
Student: Student [name=a0, roll=0]
nums: 1
combined: Student [name=a0, roll=1]
Student: Student [name=a0, roll=1]
names: b1
combined: Student [name=b1, roll=1]
Student: Student [name=b1, roll=1]
nums: 2
combined: Student [name=b1, roll=2]
Student: Student [name=b1, roll=2]
names: c2
combined: Student [name=c2, roll=2]
Student: Student [name=c2, roll=2]
...
首先与names
保持安静:
Start waiting
nums: 0
names: a0
nums: 1
names: b1
nums: 2
names: c2
nums: 3
names: a3
...
注意: