gpt4 book ai didi

android - 奇怪的 LiveData 行为与 ObservableField

转载 作者:搜寻专家 更新时间:2023-11-01 09:31:36 28 4
gpt4 key购买 nike

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

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

为什么 LiveData 不会为每个单独的 setValue 触发 onChange?

View 模型:

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

关于android - 奇怪的 LiveData 行为与 ObservableField,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46848609/

28 4 0