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

Brett May

07/30/2021, 7:57 AM
I was wondering if it is possible to use MutableStateOf with a Delegates.observable ? I want to know inside my ViewModel() subclass when my MutableState variable changes. I am looking for an equivalent of the following SwiftUI code:
Copy code
@Published var meInformation : Me? {
        didSet {
           print("MeInformation changed: \(meInformation)")
        }
    }
This doesn’t compile for me: (unresolved reference: by)
Copy code
class AuthenticatedUser(val context: Context) : ViewModel() { 
    var meInformation: MutableState<MeInformation?> = mutableStateOf(null) by Delegates.observable("<no name>") {
        prop, old, new ->
        println("$old -> $new")
    }
}
I’m not sure if it matters (being new to Kotlin), but meInformation is a @Serializable object
d

divid3d

07/30/2021, 8:24 AM
I think
MutableStateFlow
and
StateFlow
are what might you looking for. https://developer.android.com/kotlin/flow/stateflow-and-sharedflow
a

Adam Powell

07/30/2021, 1:25 PM
Can you say a bit more about the specific use case? There are a few different tools or patterns available depending on the data flow you're looking to create
b

Brett May

07/31/2021, 1:59 AM
Sure, externally to AuthenticatedUser I want the UI to redraw when the meInformation updates (info about the current user, including purchase info), internally when meInformation is updated I want this class to write this information to the sharedPreferences.
divid3d I think you are correct, looking at that link seems to fit with what I want to do.
215 Views