enisn / Xamarin.Forms.InputKit

CheckBox, Radio Button, Labeled Slider, Dropdowns etc.
MIT License
579 stars 98 forks source link

Consider how you subscribe to events #321

Closed michaelstonis closed 1 year ago

michaelstonis commented 1 year ago

Describe the bug For many controls, you are subscribing to events (+=) in the constructor using lambdas or without any destructors (-=). These event subscriptions are going to make the objects unavailable for garbage collection. In the case where lambdas are being used, those should be replaced with concrete handler methods because lambdas cannot be unsubscribed.

To solve this issue, you should consider using weak event subscriptions or adding/removing handlers as part of a control's lifecycle, such as during OnHandlerChanging or OnHandlerChanged.

To Reproduce Steps to reproduce the behavior:

  1. Create an AdvancedEntry
  2. try to garbage collect it.

Expected behavior Controls should be available for garbage collection.

Additional context Handler Lifecycle

Weak Event Manager

Here is an example of how it could be changed for AdvancedEntry.

protected override void OnHandlerChanging(HandlerChangingEventArgs args)
{
    txtInput.Completed -= ///method...
    txtInput.Focused -= ///method...
    txtInput.Unfocused -= ///method...

    if (args.NewHandler is not null)
    {
        txtInput.Completed += ///method...
        txtInput.Focused += ///method...
        txtInput.Unfocused += ///method...
    }
}