Welcome to Software Development on Codidact!
Will you help us build our independent community of developers helping developers? We're small and trying to grow. We welcome questions about all aspects of software development, from design to code to QA and more. Got questions? Got answers? Got code you'd like someone to review? Please join us.
Post History
I agree with you in that using MutableLiveData for achieving this feels wrong. I think this is because: LiveData is meant for sending data to LifecycleOwners such as Activity or Fragment, abstra...
Answer
#1: Initial revision
I agree with you in that using `MutableLiveData` for achieving this feels wrong. I think this is because: - `LiveData` is meant for sending data *to* `LifecycleOwner`s such as `Activity` or `Fragment`, abstracting the lifecycle away, and your workaround sends data in the opposite direction. - as a result, if your `View` happens to send data by through `MutableLiveData` while the lifecycle is stopped or paused, any callback you attach on the `MutableLiveData` on the `ViewModel` side simply will not run, which is probably not what you would expect. - afaik `View`s are not `LifecycleOwner`s in the first place. ----- What I've seen in most projects when they want to react to a Button click is that the Activity sets a View.OnClickListener as an anonymous class: ``` class MyActivity: Activity() { private lateinit var viewModel: MyViewModel override fun onCreate(...) { super.onCreate(...) viewModel = .... myButton.setOnClickListener { viewModel.myActionTriggered(...) } } } ``` So to me, it makes sense to do something along those lines in your case too: ``` class MyActivity: Activity() { private lateinit var viewModel: MyViewModel override fun onCreate(...) { super.onCreate(...) viewModel = .... myCanvas.setListOfPointsListener { points -> viewModel.onListOfPointsChanged(points) } } } ``` This way: - neither the `Activity` nor the `ViewModel` need to implement the ad-hoc interface - the `ViewModel` doesn't need to expose anything "mutable" - the `LiveData` get data out of the `ViewModel` to the `Activity` as it should, not the other way around - the `ViewModel` can still get the data from the `View` even when the lifecycle is "off", and it still can change its internal state in this case (other than posting to other `LiveData`, which would not work until the lifecycle is back "on") ---- A little off-topic comment: I think the name of `ListOfPoints` does not reflect what your interface does does. Your Activity doesn't become a "list of points", but rather a list of points *listener*. It doesn't contain the points itself, it just does something whenever that list changes.