我在我的存储库中使用AsyncTask,用于在存储库中设置LiveData。如何使用转换从我的ViewModel中观察此LiveData?
答案 0 :(得分:3)
你可以忽略我的其他答案。解决方案是使用MediatorLiveData<>在您的视图模型中。您将LiveData作为数据源从存储库添加到MediatorLiveData<>并在观察者onChanged回调中调用setValue或postValue(取决于它是否在UI中)。
喜欢这样
currentTransaction.addSource(application.getFinanceRepository().getTransaction(id),
new Observer<Transaction>() {
@Override
public void onChanged(@Nullable Transaction transaction) {
//Updates the MediatorLiveData<> that you activity is observing
currentTransaction.setValue(transaction);
}
});
答案 1 :(得分:1)
所以今天我正在尝试这件事而无法让它发挥作用。我试过了两个
Transformations.switchMap(application.getFinanceRepository().getTransaction(id),
new Function<Transaction, LiveData<Transaction>>() {
@Override
public LiveData<Transaction> apply(Transaction input) {
Log.d(TAG, "apply: VIewModel Transaction changed: " + input.toString());
//Set the inital transaction to track changes
initialTransaction = input;
//Update the transaction observed by the activity/fragment
currentTransaction.setValue(input);
return currentTransaction;
}
});
和
Transformations.map(loading,
new Function<Transaction, Object>() {
@Override
public Object apply(Transaction input) {
//Set the inital transaction to track changes
initialTransaction = new Transaction(input);
//Update the transaction observed by the activity/fragment
currentTransaction.setValue(input);
return null;
}
});
其中currentTransaction是MutableLiveData,而initalTransaction只是一个Transaction对象。 application.getFinanceRepository()。getTransaction(id)返回一个LiveData
此编译正常但未正常运行。从未调用apply(),我留下了一个null Transaction。我无法弄清楚如何装载它。
为了使其工作,我将application.getFinanceRepository()。getTransaction(id)返回到片段/活动。然后,观察者将调用viewModel中的方法,将Transaction返回给视图模型
public void transactionLoaded(Transaction transaction) {
initialTransaction = new Transaction(transaction);
currentTransaction.setValue(transaction);
}
然后我还将活动设置为也观察currentTransaction的MutableLiveData
希望能够清理我所做的事情的更多片段。
viewModel.loadTransaction(id).observe(this, new Observer<Transaction>() {
@Override
public void onChanged(@Nullable Transaction transaction) {
viewModel.transactionLoaded(transaction);
}
});
viewModel.getTransaction().observe(this, new Observer<Transaction>() {
@Override
public void onChanged(@Nullable Transaction trans) {
//When new LiveData arrives update the transaction and then the views
Log.d(TAG, "onChanged: transaction changed: " + trans.toString());
transaction = trans;
updateViews();
}
});
private Transaction initialTransaction;
private final MutableLiveData<Transaction> currentTransaction = new MutableLiveData<>();
public LiveData<Transaction> loadTransaction(int id) {
return application.getFinanceRepository().getTransaction(id);
}
public void transactionLoaded(Transaction transaction) {
initialTransaction = new Transaction(transaction);
currentTransaction.setValue(transaction);
}
它不理想,因为除非片段/活动参与但它确实起作用,否则它将不起作用。