语境
使用MutableLiveData保存的值。Button单击应该增加值。
问题
MutableLiveData'sObserver.onChanged()似乎在MutableLiveData.setValue()用于更改值之前被调用。
例如,在Button单击之前,onChanged日志发生在初始值设置之后(onChanged纳秒大于新值纳秒)。但是,Button单击后,onChanged日志发生在设置新值之前(onChanged纳秒小于新值纳秒)。为什么会发生这种情况?:
Button单击之前(onChanged日志预期在设置初始值后发生):
09-06 20:30:47.877 com.example.android.test D/TAG: initial set val ns 102107899222617
initial get val ns 102107899367096
09-06 20:30:47.882 com.example.android.test D/TAG: onChanged integer 0 ns 102107903996992
单击按钮后(在设置新 val 之前意外发生onChanged日志):
09-06 20:30:55.372 com.example.android.test D/TAG: onChanged integer 1 ns 102115394178238
09-06 20:30:55.373 com.example.android.test D/TAG: onClick set new val 1 ns 102115394446415
代码
final MutableLiveData<Integer> val = new MutableLiveData<>();
val.setValue(0); // triggers onChanged
Log.d(TAG, "initial set val ns " + System.nanoTime());
tv.setText("" + val.getValue());
Log.d(TAG, "initial get val ns " + System.nanoTime());
val.observe(this, new Observer<Integer>() {
@Override
public void onChanged(@Nullable Integer integer) {
// onChanged happens after initial setValue but before setValue with new value
Log.d(TAG, "onChanged integer " + integer + " ns " + System.nanoTime());
tv.setText("" + integer);
}
});
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// setting new value (triggers onChanged but
// onChanged happens before setting new value via setValue)
int newVal = val.getValue() + 1;
val.setValue(newVal);
Log.d(TAG, "onClick set new val " + newVal + " ns " + System.nanoTime());
}
});
相关分类