Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
[android] fix memory leak with
CarouselView
Fixes: dotnet#17726 Adding `CarouselView` to a page and navigating away from it keeps the page alive forever on Android. I was able to reproduce this in a test. It took me a while to actually track this one down, but the problem boils down to `MauiCarouselRecyclerView` doing: _carouselViewLayoutListener = new CarouselViewwOnGlobalLayoutListener(); _carouselViewLayoutListener.LayoutReady += LayoutReady; ViewTreeObserver.AddOnGlobalLayoutListener(_carouselViewLayoutListener); The `ViewTreeObserver` lives longer than the page, and so: * `ViewTreeObserver` -> `CarouselViewwOnGlobalLayoutListener` * `event LayoutReady` -> `MauiCarouselRecyclerView` * `MauiCarouselRecyclerView` -> `CarouselView` * `CarouselView` -> `Parent.Parent.Parent.*` -> `Page` Thus the `Page` lives forever. If we remove the `LayoutReady` event, instead: * `CarouselViewwOnGlobalLayoutListener` saves `MauiCarouselRecyclerView` in a weak reference. * It can just call `LayoutReady()` directly. * `MauiCarouselRecyclerView` is able to be GC'd now. * `MauiCarouselRecyclerView.Dispose()` already appropriately will call `ClearLayoutListener()` * Lastly, `ViewTreeObserver?.RemoveOnGlobalLayoutListener(_carouselViewLayoutListener)` With these changes, the test passes and I don't think anything will leak now. :) Other changes: * I fixed the typo in `CarouselViewwOnGlobalLayoutListener`. * I sorted the type names in the test alphabetically.
- Loading branch information