Hi everyone, happy Monday. Question: I understand ...
# compose
c
Hi everyone, happy Monday. Question: I understand that a ViewModel should not reference an Activity, or Context, or View, lest they be retained across configuration changes. Does this restriction apply to Composables as well? Or can I have a ViewModel that references something which has a @Composable method? e.g:
Copy code
class MyViewModel : ViewModel() {
  val plugin: Plugin
  ...
}

interface Plugin {
  @Composable
  fun Content()
}
My use case is, in my app we can dynamically load plugins depending on user requirements. These plugins themselves have composable methods to draw UI, and their own ViewModels in turn. Thanks for any help!
a
For the purposes of this question you can consider a
@Composable
function to be like a factory for UI rather than UI itself. When a composable is called during composition it creates an instance of that UI in the composition, not in your
ViewModel
or
Plugin
. As such, it's as safe to do what your example does as it is to keep a factory in your
ViewModel
- if the
Plugin
maintains private state based on calls to
Content
you could potentially get yourself into trouble, but hopefully it's enough to say, "don't do that" 🙂
c
Thanks for responding! Good to know
👍 1
a
in particular, private state that
Content
isn't configured to clean up for you; if a
Plugin
maintained private state using `DisposableEffect`s you'd be fine, since the effect would clean up itself and presumably that lingering private state when the call to
Content
leaves the composition/the composition is torn down
c
thanks for the tip