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

birdsofparadise

12/24/2020, 11:47 PM
Copy code
class MyActivity: AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        setContent {
            val navController = rememberNavController()
            NavHost(navController, startDestination = "") {
                composable("") { TestCompose() }
                composable("test") { TestCompose() }
            }
        }
    }
}

@Composable
fun TestCompose(vm: TestViewModel = viewModel()) {

}
Reading about the API viewModel it seems like using it in the manor I am, it's lifecycle gets attached to
MyActivity
and thus if I navigate multiple
TestCompose
views it will leak my ViewModel
z

ziv kesten

12/25/2020, 7:33 AM
If you inject the view model to the activity and pass it down the composables tree as a paramater the VM would be scoped to the main activity and would not leak from there, if you wish to have a VM for each composable you would need as of (DEC 2020) to wrap each screen with a fragment and scope the vm to the fragment.
b

birdsofparadise

12/25/2020, 4:54 PM
So what I'm doing would leak the VM?
z

ziv kesten

12/25/2020, 5:08 PM
Yes, VM, at least the android one, is scoped to a lifecycle owner, a composable is not a lifecycleowner so it would look like you are making multiple VM all scoped to main activity.
b

birdsofparadise

12/26/2020, 3:06 AM
@Adam Powell I can't find this issue in the Android bug tracker. I'm guessing its not a high priority, but it seems like something will need to be fixed in the long term. I'm wondering if you think I should open up an issue for it? Thank you
a

Adam Powell

12/26/2020, 4:02 AM
Feel free, file it to the navigation component. If there is one already it'll be duped against it
i

Ian Lake

12/29/2020, 11:19 PM
Navigation already scopes your ViewModels to that
composable
destination, not your activity, so that code is fine
👍 1
b

birdsofparadise

12/30/2020, 1:03 AM
Oh!
thats good to hear
2 Views