Hey guys, I have a question about `setContent{}`. ...
# compose
k
Hey guys, I have a question about
setContent{}
. I have a shared viewModel between a Fragment and an Activity. In the activity xml I have a
ComposeView
and in
onStart
I’m attempting to update that ComposeView like this
Copy code
Code block 1
Inside the composable view is something like
Copy code
Code block 2
The problem is that
setContent
in the activity is only being called when the activity is attached/detached. It is not observing the data stream but if it switch the code to this(still in onStart):
Copy code
Code block 3
This works fine. Is there something I’m missing about setContent{} in the Activity?
🧵 1
k
I thought you were supposed to call setContent in onCreate not onStart
k
@kevindmoore no matter, same result
Copy code
viewFromXml.setContent {
    Theme {
        ComposableView(
            viewModel = viewModel
        ) { someVal ->
            doSomeStuff(someVal)
        }
    }
}
Copy code
ComposableView(
  viewModel: ViewModel){ 
  val state = viewModel.subscribeAsState
...
...
Copy code
viewModel.subscribe({ state ->
            viewFromXml.apply {
                setContent {
                    Theme {
                        Composableview(
                            state = state
                        ) { someVal ->
                            doSomeStuff(someVal)
                    }
                }
            }
        }
}
k
Hmm. I've never seen it done this way. Can you have a field in the model that you can use Compose rememberState calls with? I think you are mixing old with new
k
I’m working with legacy code so unfortunately some things need to remain xml. I think it’s pretty common to pass a viewmodel into the composable function and observe it’s state to trigger recomposition. https://developer.android.com/jetpack/compose/libraries I have this
<ComposeView>
at the activity level and the changes in this SharedViewModel state are coming from a Fragment. The Fragment which shares this ViewModel, observes the state changes just fine. If I trigger the Activity lifecycle changes,
onStop
and then back to
onStart
. Then
setContent{}
called again and the
ComposableView(viewmodel)
then observes the latest state and updates.