'How to eliminate passing View Model to this Jetpack Compose Kotlin Home Screen?

I'm trying to clean-up my code and eliminate View Models where not necessary.

I'd like to be able to access itemList, filtering, and itemListFiltered in my HomeScreen function without explicitly passing the MainViewModel as a parameter, but I can't figure out how to do it.

I tried using itemList = model::itemList but Android Studio gives error: Type mismatch. Required: List<Int> Found: KProperty0<SnapshotStateList<Int>>

View Model

class MainViewModel : ViewModel() {

    val itemList = mutableStateListOf<Int>()

    val filtering = mutableStateOf<Boolean>(false)
    val itemListFiltered = mutableStateListOf<Int>()

    fun addItem(item: Int) {
        itemList.add(item)
    }

    fun clearItemList() {
        itemList.clear()
    }

    fun filterListGreaterThan(greaterThan: Int) {
        itemListFiltered.clear()
        itemList.forEach { item ->
            if (item > greaterThan) itemListFiltered.add(item)
        }
    }

    init {
        clearItemList()
    }   // End Initializer

}

Home Screen Scaffolding

@Composable
fun HomeScreen(
    model: MainViewModel        // <-- How do I eliminate this
) {

    val scope = rememberCoroutineScope()
    val scaffoldState = rememberScaffoldState(rememberDrawerState(DrawerValue.Closed))

    Scaffold(
        scaffoldState = scaffoldState,
        topBar = { TopBar(scope, scaffoldState) },
        floatingActionButtonPosition = FabPosition.End,
        floatingActionButton = {
            FloatingActionButton(
                onAddItem = model::addItem
            ) },
        drawerContent = {
            DrawerContent(
                onAddItem = model::addItem,
                onResetList = model::clearItemList
            ) },
        drawerGesturesEnabled = true,
        content = {
            Content(
                itemList = model.itemList,      // <-- How do I pass this itemList without model?
                onAddItem = model::addItem
            ) },
        bottomBar = { BottomBar() }
    )

}

Can you help me figure out how to do that?

Thanks for your help!



Solution 1:[1]

Pass it just like that...

model.itemsList

The :: symbol doesn't work how you seem to think it does. Consider it to be used for static non-changing variables/methods. Like you could use model::addItem or model::clearItemList since they are just public methods and do not hold a value.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Richard Onslow Roper