【发布时间】:2021-08-30 16:05:24
【问题描述】:
我创建了一个简单的应用程序,它在调用 onChanged 事件时写入日志。目前,每次我通过 setValue 增加 MyInteger 时都会调用 onChanged。我想修改所以仅针对特定事件调用 onChanged 例如仅在 MyInteger > 3 时调用 onChanged。我试图覆盖 MyInteger 中的 equals 方法,但它不起作用。我怎样才能做到这一点?
public class MainActivity extends AppCompatActivity {
private MainActivityViewModel mMainActivityViewModel;
Button button;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = findViewById(R.id.my_button);
MyInteger myInteger = new MyInteger(0);
mMainActivityViewModel = new ViewModelProvider(this).get(MainActivityViewModel.class);
mMainActivityViewModel.getLiveData2().observe(this, new Observer<MyInteger>() {
@Override
public void onChanged(MyInteger myInteger) {
Log.d("onChanged:", String.valueOf(myInteger.integer));
}
});
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
myInteger.incrementByOne();
mMainActivityViewModel.getLiveData2().setValue(myInteger);
}
});
}
}
public class MainActivityViewModel extends AndroidViewModel {
public MutableLiveData<MyInteger> myIntegerMutableLiveData;
public MainActivityViewModel(@NonNull Application application) {
super(application);
}
public MutableLiveData<MyInteger> getLiveData2() {
if (myIntegerMutableLiveData == null) {
myIntegerMutableLiveData = new MutableLiveData<>();
}
return myIntegerMutableLiveData;
}
}
public class MyInteger {
MyInteger object.
public int integer;
public MyInteger(Integer integer) {
this.integer = integer;
}
public void incrementByOne() {
integer++;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
MyInteger myInteger = (MyInteger) o;
return myInteger.integer > 3;
}
@Override
public int hashCode() {
return Objects.hash(integer);
}
}
【问题讨论】:
-
这不就是一个简单的 if 语句吗?我很困惑..
-
我希望 onChanged 隐式处理事件。我相信有一种方法可以使用 Transformations 类中的 distinctUntilChanged 方法来做到这一点。
标签: java android equals android-livedata