https://kotlinlang.org logo
Title
a

Ali Albaali

11/27/2021, 8:11 AM
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

Arkadii Ivanov

11/27/2021, 9:19 AM
Is it for desktop only?
a

Ali Albaali

11/27/2021, 9:35 AM
For now, yes.
a

Arkadii Ivanov

11/27/2021, 9:39 AM
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

Ali Albaali

11/27/2021, 9:43 AM
I have this in the screen and it's loading each time. Am I missing something?
val state by produceState<List<Item>>(emptyList()) {
    fetchItems().collect { value = it }
}
a

Arkadii Ivanov

11/27/2021, 9:47 AM
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

Ali Albaali

11/27/2021, 9:51 AM
I'm using the code from this article. I have a sealed interface
Screen
and all of the screens inherit from it.
a

Arkadii Ivanov

11/27/2021, 10:05 AM
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

Ali Albaali

11/27/2021, 10:07 AM
You mean something like ViewModel on Android which survives composition?
a

Arkadii Ivanov

11/27/2021, 10:08 AM
It would be more comparable to android fragments, but with simpler lifecycle and much less APIs
a

Ali Albaali

11/27/2021, 10:23 AM
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

Arkadii Ivanov

11/27/2021, 10:28 AM
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

Ali Albaali

11/27/2021, 11:38 AM
Ah I see. Thank you a lot, I really appreciate it :)
👍 1