Hello folks. Let's say i have a method to check in...
# android
c
Hello folks. Let's say i have a method to check internet connection inside my ViewModel that's something along these lines: internal fun callToCheckIfInternetConnectionIsAvailable( onConnectionAvailable: () -> Unit = {}, onConnectionUnavailable: () -> Unit = {} ) { if(networkChecking.checkIfInternetConnectionIsAvailable()) { onConnectionAvailable() } else { onConnectionUnavailable() } } And then i pass something like this from my Activity: viewModel.callToCheckIfInternetConnectionIsAvailable({ onConnectionUnavailable = { Toast.makeText(applicationContext, "Bla", Toast.LONG).show() } }) When it is passed to my ViewModel, it will be interpreted as a method since it's wrapped by a lambda. Although that is true, the content inside that lambda, contains lifecycle-related references such as a View. Could passing this instruction to a ViewModel cause a memory leak if the LifecycleOwner(Activity/Fragment) gets destroyed in the meantime? And besides that, would it break the MVVM pattern? Really curious to know your thoughts on the matter. Thank you in advance K
c
As far as the memory leak part, if you want to know that use https://github.com/square/leakcanary and for the MVVM part this.
c
I already have leak canary installed but it is hard to reproduce the scenario
c
Well if you already have
leakcanary
on your project, it will automatically prompt a notification when a leak has appear.
c
Unfortunately the article you sent doesn't cover my question. It's kind of a gray area so it's more specific than most cases.
s
If the lambda references view, it would crash when if view is destroyed and callback is called.
It is the same as having none lifecycle aware subscription. It leaks, crashes everything 🙂
c
Makes sense. Thank you @Saiedmomen 👍
👍 1
s
Maybe consider restructuring your logic flow to avoid this situation. Instead of passing in a lambda from your view layer risking leak, rather expose a model that encompasses the toast UI state to your livedata from your viewmodel that your view can observe on
👍 2
c
Indeed @Scott Kruse. That's exactly what I started to do today. Thanks for the tip 👍
s
no prob !