我試圖合併若干個 s在一對ReactiveList
s上創建一個ObservableAsPropertyHelper
。反應UI將Observable合併到ObservableAsPropertyHelper
public class Model : ReactiveObject {
ReactiveList<int> IngredientsEntities;
// ...
public int CostOfIngredients(...) { ... }
}
public class ViewModel : ReactiveObject {
public Model Promotion;
private ReactiveList<int> ingredientsQuantities;
private ObservableAsPropertyHelper<int> cost;
public Dictionary<..., ...> Ingredients;
public int Cost {
get { return cost.Value; }
}
public ViewModel() {
// ...
var ingredientsObservables = new[]
{
ingredientsQuantities.ItemChanged.Select(_ => Unit.Default),
ingredientsQuantities.ShouldReset.Select(_ => Unit.Default),
Promotion.IngredientsEntities.ItemChanged.Select(_ => Unit.Default),
Promotion.IngredientsEntities.ShouldReset.Select(_ => Unit.Default),
};
Observable.Merge(ingredientsObservables)
.Select(_ => promotion.CostOfIngredients(Ingredients))
.ToProperty(this, x => x.Cost, out cost);
Observable.Merge(ingredientsObservables)
.Subscribe(_ =>
{
this.Log().Info("Ingredients change detected");
});
}
}
日誌消息時將觸發,但CostOfIngredients
不會被調用,並cost
仍然null
。我在這裏做錯了什麼?
編輯:
我修改ViewModel
這現在工作:
public class ViewModel : ReactiveObject {
private int cost;
public int Cost {
get { return cost; }
set { this.RaiseAndSetIfChanged(ref cost, value); }
}
// ...
public ViewModel() {
// ...
var ingredientsObservables = new[]
{
ingredientsQuantities.ItemChanged.Select(_ => Unit.Default),
ingredientsQuantities.ShouldReset.Select(_ => Unit.Default),
Promotion.IngredientsEntities.ItemChanged.Select(_ => Unit.Default),
Promotion.IngredientsEntities.ShouldReset.Select(_ => Unit.Default),
};
Observable.Merge(ingredientsObservables)
.Subscribe(_ => Cost = promotion.CostOfIngredients(Ingredients));
}
}
我的理解是,Select(_ => Unit.Default)
創建Unit.Default
永遠不會改變的Observable
,因此從來沒有調用任何進一步Select
秒。
想知道是否將observables轉換爲IObservables <>始終w /相同的值,永遠不會改變,因爲它永遠不會改變值,因此永遠不會觸發。 – kenny 2015-02-18 17:30:53
當您說「成本保持爲零」時,您的意思是ObservableAsPropertyHelper是否爲空?在那種情況下,就好像ToProperty從未工作過。 –
Gordon
2015-02-19 01:14:34
我相信ObservableAsPropertyHelper對象是懶惰的:它不會實際訂閱並獲取設置和工作,除非您的視圖訂閱了它(綁定到成本)。這是否發生?如果是這樣,那麼其他事情正在發生。 –
Gordon
2015-02-19 01:15:52