奇怪的 LiveData 行为与 ObservableField

Strange LiveData behavior vs ObservableField

我对来自新 Android 架构组件的 LiveData 有疑问。我以前用过 ObservableField,但想试试 ACC。

当我在 Activity 中的一种方法中通过 MutableLiveData.setValue 设置值 4 次时,我只收到一次 onChange 调用,当我使用 ObservableField 而不是它时,它按我预期的方式工作 - 它点击回调 4 次.

为什么 LiveData 没有为每个单独的 setValue 触发 onChange?

视图模型:

public class MainViewModel extends AndroidViewModel {

MutableLiveData<Boolean> booleanMutableLiveData;
ObservableField<Boolean> booleanObservableField;

public MainViewModel(@NonNull Application application) {
    super(application);
    booleanMutableLiveData = new MutableLiveData<>();
    booleanObservableField = new ObservableField<>();
}

public void changeBool()
{
    booleanMutableLiveData.setValue(false);
    booleanObservableField.set(false);
    booleanMutableLiveData.setValue(true);
    booleanObservableField.set(true);
    booleanMutableLiveData.setValue(false);
    booleanObservableField.set(false);
    booleanMutableLiveData.setValue(true);
    booleanObservableField.set(true);
}
}

和Activity:

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    final MainViewModel mainViewModel = ViewModelProviders.of(this).get(MainViewModel.class);

    mainViewModel.booleanMutableLiveData.observe(this, new Observer<Boolean>() {
        @Override
        public void onChanged(@Nullable Boolean aBoolean) {
            Log.e("Mutable Value", String.valueOf(aBoolean));
        }
    });

    mainViewModel.booleanObservableField.addOnPropertyChangedCallback(new Observable.OnPropertyChangedCallback() {
        @Override
        public void onPropertyChanged(Observable sender, int propertyId) {
            Log.e("Observable value", String.valueOf(mainViewModel.booleanObservableField.get()));
        }
    });

    mainViewModel.changeBool();

}
}

堆栈跟踪:

10-20 13:34:17.445 1798-1798/com.example.livedatasample E/Observable value: false
10-20 13:34:18.588 1798-1798/com.example.livedatasample E/Observable value: true
10-20 13:34:19.336 1798-1798/com.example.livedatasample E/Observable value: false
10-20 13:34:19.994 1798-1798/com.example.livedatasample E/Observable value: true
10-20 13:34:20.892 1798-1798/com.example.livedatasample E/Mutable Value: true

LiveData 具有生命周期意识。在你的例子中,你正在改变它在 onCreate 中的值 - liveData 将在 activity 启动时调用它的观察者(在这种情况下恰好一次)。

LiveData considers an observer, which is represented by the Observer class, to be in an active state if its lifecycle is in the STARTED or RESUMED state. LiveData only notifies active observers about updates. Inactive observers registered to watch LiveData objects aren't notified about changes. https://developer.android.com/topic/libraries/architecture/livedata