@@ -556,8 +556,10 @@ internal static IDisposable OnLoaded(this View view, Action action)
556
556
EventHandler < AView . ViewAttachedToWindowEventArgs > ? routedEventHandler = null ;
557
557
ActionDisposable ? disposable = new ActionDisposable ( ( ) =>
558
558
{
559
- if ( routedEventHandler != null )
559
+ if ( routedEventHandler is not null && view . IsAlive ( ) )
560
+ {
560
561
view . ViewAttachedToWindow -= routedEventHandler ;
562
+ }
561
563
} ) ;
562
564
563
565
routedEventHandler = ( _ , __ ) =>
@@ -596,16 +598,29 @@ internal static IDisposable OnUnloaded(this View view, Action action)
596
598
EventHandler < AView . ViewDetachedFromWindowEventArgs > ? routedEventHandler = null ;
597
599
ActionDisposable ? disposable = new ActionDisposable ( ( ) =>
598
600
{
599
- if ( routedEventHandler != null )
601
+ if ( routedEventHandler is not null )
600
602
view . ViewDetachedFromWindow -= routedEventHandler ;
601
603
} ) ;
602
604
603
- routedEventHandler = ( _ , __ ) =>
605
+ routedEventHandler = ( sender , args ) =>
604
606
{
605
607
// This event seems to fire prior to the view actually being
606
608
// detached from the window
607
609
if ( view . IsLoaded ( ) && Looper . MyLooper ( ) is Looper q )
608
610
{
611
+ // We unsubscribe here because if we wait for the looper
612
+ // to schedule the work the view might get disposed by the time
613
+ // the unsubscribe code runs
614
+ if ( disposable is not null )
615
+ {
616
+ if ( args . DetachedView . IsAlive ( ) )
617
+ {
618
+ args . DetachedView . ViewDetachedFromWindow -= routedEventHandler ;
619
+ }
620
+
621
+ routedEventHandler = null ;
622
+ }
623
+
609
624
new Handler ( q ) . Post ( ( ) =>
610
625
{
611
626
if ( disposable is not null )
0 commit comments