Hi everyone I want to store data coming from APIs...
# multiplatform
m
Hi everyone I want to store data coming from APIs so that I can show the previous data to the users until new data come from the API, like we use redux in the web apps. can anyone tell me how to implement that behaviour? Thank you in advance.
m
StateFlow/MutableStateFlow.
m
but mutablestate always clear when I goto some other screen @Mats-Hjalmar
m
then make something outside of that screen hold it
m
don't we have some store like thing? @Mats-Hjalmar
m
You can create one. Make a repository that is treated as a singleton, with “UseCases” in the domain layer to expose this StateFlow.
m
@Mats-Hjalmar I'm a beginner can I have a guide or something for reference? Thank you for your time sir.
m
Copy code
class Foo {
    private val _goo = MutableStateFlow(0)
    val goo = _goo.asStateFlow()
}

@Composable
fun Roo() {
    val foo = remember { Foo() }
    val goo by foo.goo.collectAsState()
    // Navigation inside this composable.
}
m
But is it safe to use singleton as a store? @Mats-Hjalmar?
In my R&D singleton should use as a resource management
Can anyone help?
p
you can use a local db, like sqldelight
m
Is it available for both platforms and is it performance friendly?
@Priyansh Nama?
e
I think you can use common View Models but it is still experimental
m
But view modals will be empty when I go to other screens. @Esteban Vasquez
I want to persist the data
Can any life saver here?
p
assuming the older data is stored in local db in your repository create a function suspend fun getData() : Flow<Data> = flow{} then in this flow 1. set the data state as loading 2. check if local data exists if(data exists) { emit Data Local Success with data } and continue the function, no matter if data is present or not then make the api call (suspending) and emit the result with Data Success with data this way, you first emit the local data (if present) then wait for api call to finish to show latest data
🙌 1