我写了一个简单的例子,希望有人能帮助我理解这段代码,以及为什么它两次在Bifunction中将文本打印两次:
var subject1: BehaviorSubject<String>? = null
var subject2: BehaviorSubject<String>? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
Log.v("mytag", "oncreate called now")
subject1 = BehaviorSubject.createDefault("hello")
subject2 = BehaviorSubject.createDefault("goodbye") //not subscribed to
subject1?.subscribe { Log.v("subject1 it1", it) }
btn.setOnClickListener {
subject1?.onNext("hello btnclicked" + Random().nextInt(9000))
ObservableCombineLatest.combineLatest(
subject1,subject2, BiFunction<String,String,String>
{ t1, t2 -> "biFun call" }).
subscribe { msg-> Log.d("mytag","combined latest update: $msg")}
}
}
}
当我单击第一次尝试的按钮时,这是输出:
07-13 00:55:09.124 10559 10559 D mytag : combined latest update: biFun call
07-13 00:55:09.130 10559 10559 D mytag : combined latest update: biFun call
但是为什么呢?只有一个主题已更改,thats subject1变量。当我单击按钮时,其调用onNext会开始发射。为什么要打印两次?我期望由于从未使用subject2,因此不会触发。
答案 0 :(得分:1)
这对我有用:
import org.junit.Test;
import io.reactivex.subjects.BehaviorSubject;
import io.reactivex.Observable;
public class BehaviorSubjectCombineLatest {
BehaviorSubject<String> subject1;
BehaviorSubject<String> subject2;
@Test
public void test() {
subject1 = BehaviorSubject.createDefault("hello");
subject2 = BehaviorSubject.createDefault("goodbye");
subject1.subscribe(v -> System.out.println("Subject1 it1: " + v));
click();
}
void click() {
subject1.onNext("hello button clicked " + System.currentTimeMillis());
Observable.combineLatest(subject1, subject2,
(a, b) -> "biFun call " + a + ", " + b)
.subscribe(v -> System.out.println("Combined latest: " + v));
}
}
打印:
Subject1 it1: hello
Subject1 it1: hello button clicked 1531467839204
Combined latest: biFun call hello button clicked 1531467839204, goodbye
但是,如果多次“单击”,则会创建越来越多的combineLatest
,从而产生更多重复的打印输出。单击三下:
Subject1 it1: hello
Subject1 it1: hello button clicked 1531467945206
Combined latest: biFun call hello button clicked 1531467945206, goodbye
Subject1 it1: hello button clicked 1531467945240
Combined latest: biFun call hello button clicked 1531467945240, goodbye
Combined latest: biFun call hello button clicked 1531467945240, goodbye
Subject1 it1: hello button clicked 1531467945242
Combined latest: biFun call hello button clicked 1531467945242, goodbye
Combined latest: biFun call hello button clicked 1531467945242, goodbye
Combined latest: biFun call hello button clicked 1531467945242, goodbye