is it a good practice to have a state flow in a si...
# compose
p
is it a good practice to have a state flow in a singleton and to access it in a viewmodel to make changes on a screen depending of the value of that state flow?
p
Singleton is considered an antipattern
p
well, in some circunstances is a good option, even in google android courses and codelab they are using it and recommending it
👍 1
maybe can someone tell me if is a good practice to use the state flow outside a composable and a viewmodel? in an external object like a singleton? thanks
🚫 1
r
there's no rules that say where a state flow should be. It's up to you to determine and make sure you don't have memory leaks or components living past their intended lifecycle.
on Android, using the application reference or a singleton is very similar conceptually. And iOS makes extensive use of singletons too.
p
thank you
a
You can have the stateflow as a global val, why bother adding it to a singleton (object)
I do that often, only in POCs
p
well, it feels more confortable to have it on the singleton that manages sections
a
Okay
I wouldnt do it either way in a well designed app
Not sure abt your use case though, maybe it makes sense
p
yes it does, is not a normal app, is a meta app that displays an app defined in a json, so is not a common way to do it
a
What does meta app mean?
r
in my opinion, it is good practice to manage the lifecycle of your "holders". Your singleton could instead be an instance that you instantiate yourself and make sure other child components get a reference to, if needed. If anything, it forces you to re-think and double check when and where something is needed. Otherwise you quickly end up with tons of singletons holding little pieces of state which is hard to reason about and as mentioned can lead to memory leaks.
👍 1
p
well, it's an app that can be infinite apps with the same source code, I mean, depending on the json received can generate a different app. So, one element can have an event with infinite actions, one of these actions can be a screen change with more following actions in the same event
as you notice is not possible to change the current screen simply hoisting an "onscreenchanged" event with the current screen, there are infinite possibilities and chained actions/events
so the only way I found to manage screen changes is with a "currentScreen" stateflow in a globally accesed class, in this case I'm using the screen manager class that does some other tasks
a
Probably you need to take a look at the compose navigation library
p
I'm already using it
110 Views