I have an app which fetches a list of posts from a...
# compose-desktop
a
I have an app which fetches a list of posts from an API. The app uses Decompose for navigation. I'm wondering what's the best way to persist the list so the list is still available even after navigating to a different destination. Should I save it using
rememberSaveable()
, Decompose's
InstantKeeper
or
StateKeeper
, or an embedded SQLite database, thoughts?
a
Is it for desktop only?
a
For now, yes.
a
So if it's desktop only, then you can just keep a reference to the list in the screen's component. Usually there should be something like
MutableState<List<Item>>
or similar. Then when you push/pop screens, the previous screen`s component will not be destroyed.
a
I have this in the screen and it's loading each time. Am I missing something?
Copy code
val state by produceState<List<Item>>(emptyList()) {
    fetchItems().collect { value = it }
}
a
This code seems unrelated to Decompose. Would be good to see more code. When using Decompose, each screen is usually represented as a class.
a
I'm using the code from this article. I have a sealed interface
Screen
and all of the screens inherit from it.
a
Right. The article is quite outdated already, I should update it with this information. Basically when another screen is pushed to the stack, the previous Composable leaves the composition. All remembered state is lost. You can try using rememberSaveable, it should help. But personally I recommend using classes. This may look like more boilerplate, but it also gives more power. Here is the tutorial: https://github.com/JetBrains/compose-jb/tree/master/tutorials/Navigation#managing-navigation-outside-composable-world
a
You mean something like ViewModel on Android which survives composition?
a
It would be more comparable to android fragments, but with simpler lifecycle and much less APIs
a
In the tutorial you have mentioned, I'm using the second approach "Managing navigation inside @Composable world", are you implying I should change it to the first one?
a
The second approach is valid, but it has the side effect you are experiencing. So rememberSaveable should help in your case. But it will stop working if you add Android in the future. To keep this approach working with Android, you will need to make items Parcelable.
a
Ah I see. Thank you a lot, I really appreciate it :)
👍 1