Skip to content

Commit eb8e804

Browse files
jfversluisPureWeen
andcommitted
Add defensive IsAlive check to Android ViewExtensions.OnUnloaded (#29934)
* Update ViewExtensions.cs * Update ViewExtensions.cs * Update ViewExtensions.cs * - unsubscribe sooner --------- Co-authored-by: Shane Neuville <[email protected]>
1 parent f2dd2ca commit eb8e804

File tree

1 file changed

+18
-3
lines changed

1 file changed

+18
-3
lines changed

src/Core/src/Platform/Android/ViewExtensions.cs

Lines changed: 18 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -556,8 +556,10 @@ internal static IDisposable OnLoaded(this View view, Action action)
556556
EventHandler<AView.ViewAttachedToWindowEventArgs>? routedEventHandler = null;
557557
ActionDisposable? disposable = new ActionDisposable(() =>
558558
{
559-
if (routedEventHandler != null)
559+
if (routedEventHandler is not null && view.IsAlive())
560+
{
560561
view.ViewAttachedToWindow -= routedEventHandler;
562+
}
561563
});
562564

563565
routedEventHandler = (_, __) =>
@@ -596,16 +598,29 @@ internal static IDisposable OnUnloaded(this View view, Action action)
596598
EventHandler<AView.ViewDetachedFromWindowEventArgs>? routedEventHandler = null;
597599
ActionDisposable? disposable = new ActionDisposable(() =>
598600
{
599-
if (routedEventHandler != null)
601+
if (routedEventHandler is not null)
600602
view.ViewDetachedFromWindow -= routedEventHandler;
601603
});
602604

603-
routedEventHandler = (_, __) =>
605+
routedEventHandler = (sender,args) =>
604606
{
605607
// This event seems to fire prior to the view actually being
606608
// detached from the window
607609
if (view.IsLoaded() && Looper.MyLooper() is Looper q)
608610
{
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+
609624
new Handler(q).Post(() =>
610625
{
611626
if (disposable is not null)

0 commit comments

Comments
 (0)