语境使用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 10210789936709609-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 10211539417823809-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 onChangedLog.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()); }});
添加回答
举报
0/150
提交
取消