# compose


12/09/2021, 4:56 PM
I have a
variable inside a shared ViewModel which lives with in the app scope and not inside a specific route. I use this view inside one of my routes. My issue is that if the screen is rotated or the route is navigated to again from itself, loading the view throws an exception since the view is still attached to the previous layout parent. I know the fix for this is to have at least 2 instances of the view I need but the issue is that composable lifecycles work a bit weirdly and I cannot figure out exactly how and when I should tell the ViewModel to switch the used view so it wont throw an exception. More in 🧵
I currently managed to fix the route re-navigation crash using 2 instances of my viewmodel but the viewmodel is switched whenever the screen is renavigated to so it still crashes on rotation.
Any ideas would be great 😩

Chris Fillmore

12/09/2021, 5:14 PM
In general, I think keeping a View in your ViewModel is not a good idea. It is probably simpler for you to solve this problem (i.e. don’t reuse your View), than the problem of how to persist your View across lifecycles (which Android doesn’t expect, and doesn’t want, you to do). Why is your View so expensive to create? What is it doing? Could some of its behaviour be offloaded to some data component?


12/09/2021, 5:24 PM
Yeah but the issue is that the view I am trying to keep in memory takes 5-10 seconds to load (its a YouTube player WebView from this library). Thats why I am trying to keep it in a shared view model. It is currently separated in the non develop version of the app.
And the other part of the issue is that the View is bugged when I create it inside my route directly (weirdly just never fully loads on some devices) which is just a bug inside the library I am using but unfortunetly I dont have any real options for alternative libraries.
Unless I create my own which is time consuming.
I was originally trying to fix the issue with the webview not fully loading on some devices and realized for some reason the issue does not happen when the webview is created inside a viewmodel so I thought I should use it this way now since it also improves the user experience by decreasing the load time.
Now that I think about it, it might be due to the view being created using application context in the viewmodel. 🤔