Seems HorizontalPager doesn’t dispose a composable...
# compose-android
c
Seems HorizontalPager doesn’t dispose a composable, I have 3 pages with an event inside a
LaunchedEffect
using Unit as key in each page, but it gets called first time then anytime the page has been disposed by the Pager. Is there any way around that behavior? I just want when a user switches a page the previous page should be disposed.
s
What do you mean by saying that it doesn't get disposed, and then by saying that launched effect gets called every time it gets disposed? I'm not sure what you are trying to achieve exactly and what you're getting instead.
c
So I have 3 pages basically, each page displays a list, I used a Launched effect to get the list first time. So let’s say the user switches to page 2, page 1 will still be in memory because when the user navigates back to page 1 the launched effect will not be triggered.
As the first page has not been disposed when the user switches to page 2
But if the user switches to page 3, page 1 will be disposed and behave as if it’s just entering the composition
x
There’s something in what you say that seems odd to me. When you do: 1. Get page 1 2. Navigate to page 2 3. Go back to page 1 It would be expected that the
LaunchedEffect
is triggered in all the page changes, as you’re entering the composition phase with each change
c
It doesn’t. If you also add a
DiposableEffect
,
onDispose{}
will not be called when you navigate to page 2
s
Don't do this effect using LaunchedEffect then, since it will change behavior depending on what you set your beyondBoundsPageCount as. Do this effect as a result of listening to the current page of your PagerState instead?
Relying on when it gets disposed sounds like an easy way to make it harder for yourself.
c
So I thought the pages will recompose each time I navigate to it.
s
LaunchedEffect(Unit) doesn't trigger on each recomposition, but on each time it enters composition while it wasn't there before. Those two things are very different things.
If you need to do something every time page number X is shown, you just do that precisely, don't rely on such behaviors like how long the lazy row will decide to keep off-screen items in memory or whatever. Does pagerState expose some sort of
currentPage
out in it's public API? Preferably one that's backed by mutable state? If yes, you can do
Copy code
val pagerState = rememberPagerState(...)
LaunchedEffect(Unit) {
  snapshotFlow { pagerState.currentPage }
    .filter { it == X }
    .collect { \\ or collectLatest, depending on what you need.
      doSomething()
    }
}
x
Interesting, I was wrong then in assuming that
LaunchedEffect
would be triggered in any recomposition. What you're saying here makes sense to me, thanks for the explanation!
130 Views