How do you ask questions of, or send requests to, ...
# compose
r
How do you ask questions of, or send requests to, nested Composables? Here’s a simplified example in thread.
Copy code
fun Outer() {
   val thing = pieceOfViewModel()
   Column {
      BackButton() {
          if (inner editor is valid) { save() }
          else { showInnerEditorsAlert() }
      }
      InnerEditor(thing)
   }
}

fun InnerEditor(thing: Thing) {
    val text = remember { mutableStateOf("") {    
    // some editor controls
    // if text is "valid" then it would want to let the back button work in Outer
}
k
Use a shared boolean mutable state in Outer, with InnerEditor changing and Outer looking at it for the conditional logic
r
@Kirill Grouchnikov That
isValid: Boolean
mutable state would need to be computed and set on every change, inside InnerEditor. But I want it to be lazy, only computed when the person tries to go "back" in Outer.
z
It seems like your entire inner state should be hoisted out, and then you can calculate that valid flag whenever you want (eg it can be a computed property if you want)
r
I can't do that (easily) because there is an abstraction barrier between Inner and Outer. In the real code, the "Inners" are filters in a search system. The outer has a handle to an abstract Filter and calls its
@Composable EditScreen(...)
method, which each Filter overrides differently. So if I hoist the Inner/Filter state, I need to create an abstract
InnerState
which all the different Inners could implement differently. I may try that, but it may be more complicated than the hack I came up with yesterday, which was to remember a coroutine
Channel
in Outer and send a message "downward" into Inner with that.
k
In general, if I may. I spent the first few months of working with Compose sort of fighting against it. I was trying to find "clever" ways to bring imperative thinking and concepts into this reactive world. IMO it's not worth it, especially in the long run for readability and maintainability of the codebase. One of the more useful mental models to break, if you will, is to stop seeing the UI tree as something that exists as a tree - where any node can "peek" into any other node if it has a reference to it. I stopped seeing composables as a tree. Once I broke away from that model, I stopped looking for hacks and started looking for the "correct" ways to share and propagate state.
☝️ 2
☝🏻 1