Search code examples
bindingmvvmcrossweak-references

FieldBinding and weak reference


I was willing to use the INC<T> version of the notify property change mecanism, which is much more concise than the Property + Field + RaisePropertyChanged version.

BUT, let say I have this ViewModel:

public abstract class PageViewModel : MvxViewModel
{
    /// <summary>
    ///     The is loading
    /// </summary>
    public readonly INC<bool> IsLoading = new NC<bool>();

    /// <summary>
    ///     The subtitle
    /// </summary>
    public readonly INC<string> Subtitle = new NC<string>();

    /// <summary>
    ///     The title
    /// </summary>
    public readonly INC<string> Title = new NC<string>();

Now, let say I am in my android Activity, and I want to subscribe to these properties :

public partial class MainView : IFragmentHost
{
    private void Subscribe(PageViewModel viewModel)
    {
        viewModel.Title.Changed += (xx) => Whatever;
    }

On a second though, it would be nice to WeakSubscribe to them so:

 viewModel.Title.WeakSubscri...

Mmmmh weird, I have no autocompletion on that.

Let's see the MvxWeakSubscriptionExtensionMethods:

public static class MvxWeakSubscriptionExtensionMethods
{
    public static MvxNotifyPropertyChangedEventSubscription WeakSubscribe(this INotifyPropertyChanged source, EventHandler<PropertyChangedEventArgs> eventHandler)
    {
         return new MvxNotifyPropertyChangedEventSubscription(source, eventHandler);
    }

    public static MvxValueEventSubscription<T> WeakSubscribe<T>(this EventInfo eventInfo, object source, EventHandler<MvxValueEventArgs<T>> eventHandler)
    {
         return new MvxValueEventSubscription<T>(source, eventInfo, eventHandler);
    }

And now the INC<T>

public interface INC<T> : INotifyChange<T>, INotifyChange

So, is there a way to weak subscribe to a INC<T> property ?


Solution

  • The plugin itself makes bindings using weak references using:

      IDisposable _subscription = NotifyChangeEventInfo.WeakSubscribe(_notifyChange, NotifyChangeOnChanged); 
    

    where NotifyChangeOnChanged has signature:

      protected abstract void NotifyChangeOnChanged(object sender, EventArgs eventArgs); 
    

    from https://github.com/MvvmCross/MvvmCross/blob/3.2/Plugins/Cirrious/FieldBinding/Cirrious.MvvmCross.Plugins.FieldBinding/MvxNotifyChangeFieldSourceBinding.cs#L38