Is it a good idea to call a function in the ViewMo...
# android
s
Is it a good idea to call a function in the ViewModel and pass a function as the callback instead of using LiveData or other flow? Is there any memory leak doing this?
g
When creating a callback/lambda from View, if you refer something like 'context', this, viewbinding instance or anything related to the view class, you'll leak the context (and probably the entire activity) to the ViewModel. A callback (Java or Kotlin) usually generates something equivalent to an inner class that has reference to the outer class, here the view class, so unless you clean all the callbacks when view is destroyed, you may leak. If you use Jetpack's ViewModel, then your ViewModel outlives the Fragment/Activity lifecycle and you should probably avoid keeping references to the previous ones. You can test & detect leaks with LeakCanary. The advantage of LiveData (for example) is that it's lifecycle aware and unsubscribe the callback at the right time. Also not sure if it's really a Kotlin question you have here.
s
It's a android architecture question maybe... I have something like this: when the user clicks a button I call a function in the viewmodel, it's done in the viewmodelScope coroutine, inside this scope it calls the web service in the repository to obtain a String. If I have this resulting String as a LiveData to be observed I feel like the logic flow is broken in the activity because there's an action in one place and the 'reaction' in another place.
I don't know if this makes sense
g
It doesn't make sense to me. You're crossing a boundary View <-> ViewModel here, looks logical to send some data to the view, and the view to transform this data into visual informations. If you make the transformation from data to visual information in the ViewModel, you're mixing 2 distinct roles (see SRP).
s
OK I end with setting up an observer for the result of the operation to the webservice. So user clicks to create document -> ask viewmodel for document serial from webservice -> viewmodel sets the result to LiveData which is observed in the fragment. then it continues with the creation of the document. This jump from place to place in the fragment makes me say that there's no continuation of flow. If the recommended was to allow expose suspend functions from the viewModel the logic flow would be all in one place in the fragment
whats the SRP?
g
Some links that may help: https://developer.android.com/jetpack/guide#recommended-app-arch https://en.wikipedia.org/wiki/SOLID
the logic flow would be all in one place in the fragment
IMO that's a bad take, code in fragment is hard to test, that's one of the main reason for MVVM.
👍 1
s
yes, makes sense. didn't think about the testing part
code seems to be working fine. thanks for the help