-
Notifications
You must be signed in to change notification settings - Fork 366
Description
Overview
Currently, [ObservableProperty] generates two methods to hook additional logic before or after the property value is set. These only receive the new value as input though, which makes them not enough in cases where some change also has to occur on the previous value. For instance, unselecting an item, or unregistering some event handler.
This proposal is about also generating overloads with the previous value, so developers can implement the method they need.
API breakdown
Given some bool IsSelected property, these two additional methods would also be generated:
partial void OnIsSelectedChanging(bool oldValue, bool newValue);
partial void OnIsSelectedChanged(bool oldValue, bool newValue);Usage example
Consider this scenario where a selected item also has to notify the UI of its template:
[ObservableProperty]
private ItemViewModel selectedItem;
partial void OnSelectedItemChanged(ItemViewModel oldValue, ItemViewModel newValue)
{
oldValue.IsSelected = false;
newValue.IsSelected = true;
}Additional notes
To further help users, the oldValue parameter in OnPropertyNameChanging should always be marked as nullable if the property type is a reference type, regardless of whether it's annotated as nullable. This is because the old value might be null the first time the property is set, which might instead be error prone for people accessing the property from the Changing value to try to get the old value (as the property would be annotated as potentially not nullable, even if it could actually be so in that first case).
Breaking change?
No
Alternatives
Fallback to manual properties or hook into OnPropertyNameChanging and access the old value from the property. Doable, but not really convenient. These methods are free anyway if not implemented, so we might as well give users more flexibility.