How would the @Composable ContentFeed()
function access the viewModel
which was created in the Activity? Dependency injection? Or is that a wrong way of doing things here? The viewModel
should always have only have one instance.
// MainActivity.kt
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val viewModel by viewModels<MainViewModel>()
setContent {
PracticeTheme {
// A surface container using the 'background' color from the theme
Surface(color = MaterialTheme.colors.background) {
PulseApp(viewModel)
}
}
}
}
// TabItem.kt
typealias ComposableFun = @Composable () -> Unit
sealed class TabItem(var icon: Int, var title: String, var content: ComposableFun) {
object Feed : TabItem(R.drawable.ic_baseline_view_list_24, "Feed", { ContentFeed() })
}
// Content.kt
@Composable
fun ContentFeed() {
// I need viewModel created in MainActivity.kt here
}
ViewModel
in theonCreate()
method of an activity and passing it down to all functions as an argument. So I should have just been doing instead isval viewModel = viewModel<MyViewModel>()
in all the Composable functions that require that specificviewModel
correct? – Wester