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

aipok

06/23/2020, 10:50 AM
Is there any concept in mind of how the composable should be decoupled or how big should/could be views/pages/screens with nested composable elements? Another question is, what is the best way to pass or get an instance of the ViewModel inside compose element?
Thank you for your response. I saw in examples that usually data that is passed to compose function is limited. Like what to show and callback to notify parent with an action. But that means we should not call anything in the compose and always an activity will be responsible for calling new activity or some other system actions? Or having the compose element that incapsulate some logic or have its own VM is also an option. This is what I’m trying to understand right now. Of cause I’m comparing now Compose elements with Fragments, not with custom views. But I’m not sure should I? My understanding is that compose will replace fragments and layouts, but again is it? Or should I consider compose elements only as views or sets of views?
j

jim

06/23/2020, 12:11 PM
Let me preface this by saying that much of this boils down to judgement calls on your part, because you are the one who will need to maintain your own code. That said, I can give general advice based on what I've seen people do and what tends to work/fail in my experience. As a general rule of thumb, keep your widgets as decoupled as possible. Passing in data to show and callbacks to notify parents is exactly the correct design, follow that pattern to the maximal extent possible. It will feel unfamiliar, so push past your discomfort, and your future self will thank you for it. Widgets can (and should) have their own logic, and can introduce/expose their own classes and data model types. For example, a
DatePicker
or
CreditCardEntryForm
or
AddressForm
could all have very sophisticated validation logic. If you were implementing GoogleDocs, you might have a
GoogleDocTextEditor
widget that took in a mutable
RichTextDoc
data structure describing the document. But the logic of these widgets should be self-contained to the widget's specific concerns, and not explicitly depend on the app as a whole. If your widget has a reference to your
Activity
, you're almost certainly doing it wrong. Compose widgets are certainly expected to replace Fragments in general usage, but I'd suggest using a mental model that is closer to custom views. Fragments were a very leaky abstraction that wasn't conducive to good encapsulation. Instead, you want to build reusable chunks that feel like something you could embed into another app. At some point you will intentionally break this rule, but if you feel the need to ask the question, then you're probably not yet ready to break the rule.
🖖 1