https://kotlinlang.org logo
#compose
Title
# compose
p

Paul Woitaschek

11/01/2023, 10:39 PM
When swiping this, I would have expected that every “remember page” log is only shown once. However, once swiping or just dragging a page a little left and right, the block gets called again and again. Is that expected behavior? Is there a way to remember something depending on the page?
Copy code
HorizontalPager(
    modifier = Modifier.fillMaxSize(),
    pageCount = 42
) { currentPage ->
    remember(currentPage) {
        Log.d("remember", "remember page $currentPage")
        42
    }
    Text(
        modifier = Modifier.fillMaxSize(),
        text = "Page $currentPage"
    )
}
If I make use of rememberSaveable, this works as I want. However the thing I want to remember (a presenter) actually is not saveable.
a

Albert Chang

11/02/2023, 7:39 AM
This is the expected behavior, and I don't think movable content will help here, as
movableContentOf
doesn't prevent the content inside from being disposed when the call to the movable content is disposed. You can just set a appropriate
beyondBoundsPageCount
to make sure the pages are not disposed.
p

Paul Woitaschek

11/02/2023, 7:41 AM
I tried that but when I touch a pager and drag it by a few pixels left or right it makes my app really laggy as it composes the whole time while dragging and state seems to be discarded
For that specific thing one solution I came up with (and which works) is to have my own memory cache for the objects I’m persisting, but what I really want is some: rememberSaveableInMemoryOnlyAndIgnoreBundlePersistence
e

ephemient

11/02/2023, 7:45 AM
movableContentOf
will help if you move the content outside of the pager
a

Albert Chang

11/02/2023, 7:46 AM
No it won't. You can try it yourself.
Copy code
val content = remember { movableContentOf { ... } }
content() // When this call is disposed (and not moved to anywhere else), content inside will also be disposed
And to OP, the
rememberSaveableInMemoryOnlyAndIgnoreBundlePersistence
you want is probably just something as simple as
Copy code
val map = remember { mutableMapOf<Int, Something>() }
HorizontalPager { currentPage ->
    map.getOrPut(currentCompositeKeyHash) {
        Something()
    }
}
p

Paul Woitaschek

11/02/2023, 11:00 AM
Yep that’s what I went with 👌