我有一种情况,我有一个页面的视图模型,该页面基于一些输入数据(id)呈现,其中的字段是从我的存储库初始化但可以由用户编辑。
我的存储库功能非常简单:
class AccountsRepository {
public LiveData<Account> getAccount(long id) {
return roomDb.accountDao().getAccount(id);
}
}
我希望我的视图模型可以重新用于不同的帐户,所以我有一个LiveData<Long>
将使用帐户 ID 进行设置的模型。
class EditAccountViewModel {
private MutableLiveData<Long> accountId = new MutableLiveData<>();
public void setAccountId(long id) {
accountId.setValue(id);
}
}
在我的视图模型中,我想公开一个name
绑定到EditText
视图的可变字段。该字段应由存储库中的数据初始化。如果我使用简单的不可编辑绑定,我可以让单向数据绑定工作:
class EditAccountViewModel {
private MutableLiveData<Long> accountId = new MutableLiveData<>();
public LiveData<String> name;
EditAccountViewModel() {
this.name = Transformations.map(
Transformations.switchMap(accountId, repo::getAccount),
account -> account.name);
}
}
但是,我无法使用它绑定@={viewModel.name}
它,因为它抱怨它不知道如何设置值。我尝试编写一个辅助类,这样使用底层MediatorLiveData
来设置值,但看起来我的 onChanged 回调从未被调用:
class MutableLiveDataWithInitialValue<T> extends MutableLiveData<T> {
MutableLiveDataWithInitialValue(LiveData<T> initialValue) {
MediatorLiveData<T> mediator = new MediatorLiveData<>();
mediator.addSource(
initialValue,
data -> {
// This never gets called per the debugger.
mediator.removeSource(initialValue);
setValue(data);
});
}
}
我更新了视图模型如下:
class EditAccountViewModel {
private MutableLiveData<Long> accountId = new MutableLiveData<>();
public MutableLiveData<String> name;
EditAccountViewModel() {
this.name = new MutableLiveDataWithInitialValue<>(
Transformations.map(
Transformations.switchMap(accountId, repo::getAccount),
account -> account.name));
}
}
但是,当我这样做时,我的EditText
字段永远不会设置数据库中的值,这是有道理的,因为onChanged
回调永远不会在我MediatorLiveData
的 in 中调用MutableLiveDataWithInitialValue
。
这似乎是一个很常见的用例,所以我想知道我在搞砸什么?