Hi, is there a way to know if a MutableState prope...
# compose
w
Hi, is there a way to know if a MutableState property is being observed by a Composable or is read in general?
z
Within a single thread you can add a read observer at the top of the call stack to see if anything below it does a read. But there’s no global way to do that across threads that I know of. And for composables in particular, I don’t think there’s nowhere to add that observer that would work.
w
@Zach Klippenstein (he/him) [MOD] I want something similar to subscriptionCount in MutableStateFlow, or just a boolean to check if it's free or in composition, or when it leaves all compositions.
like a callback when it's not utilized/read by anything.
z
Curious but why
z
Yea there’s nothing like that, but also curious what you’re trying to do
w
ok so the TextField API is known to have async issues of state
which forced me to use MutableState to shrink the chance of encountering the cursor falling behind of text issue
but that MutableState is wrapped in a class that plays the role of a tiny "ViewModel" that only holds that mutableState and needs to be GCed when it's not used by the view or by some other tiny "ViewModel"
since it is cached to be reused & skip creating it over and over if more than one entity needs it. It is cached globally.
I simply don't want that cache to have dead things in it aka memory leaks.
h
from what I'm understanding, you want to check whether your globally cached MutableState wrapper is holding something that is actually in use or not. Instead of trying to be clever with it, would flagging your state via DisposableEffect besides TextField work?
Copy code
DisposableEffect(textFieldViewModel) {
  textFieldViewModel.inUse = true
  onDispose {
    textFieldViewModel.inUse = false
  }
}
TextField(...)
w
Hello. Yes, using a DisposableEffect should work on paper, by implementing some sort of subCount:Int even though it will require to maintain it in two different places (the context of my project). I'm also considering WeakReferences. I'll see which one is better for the job when I implement both options. Thanks for your suggestion.