Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Mutability/Immutability state variables in viewmodel

I wanted to know what is the difference between the two approaches for settings values in the viewmodels:

Approach one is using function to set the new value to the variable. The second approach is using the setter to set the value to the variable.

I know it is not recommended to expose mutable variables to the view but the execution is the same if we call the function or set the variable in the views.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

A: 

``
class SampleViewModel(): ViewModel {
  
  private val _title = MutableLiveData<String>()
  val title: LiveData<String>
    get() = _title
  
  // Setting the title
  fun setTitle(newTitle: String) {
    _title.value = newTitle 
  }
  
}

B:

class SampleViewModel(): ViewModel {
  
  private val _title = MutableLiveData<String>()
  val title: LiveData<String>
    get() = _title
  
  
  // Setting the title
  var setTitle: String
    set(value) = {
      field = value 
      _title.value = value
    }
  
}

Any input is appreciated.

I tried both approaches and it is working fine on both cases.

>Solution :

The main difference between the two approaches is that the first approach provides more control over the variable. When using a function to set the value, you can add a validation layer to ensure that the value being set is valid. This is important for data integrity. You can also add logic to the function that will modify the value before setting it.

The second approach is simpler and more straightforward, but it does not provide as much control. It’s a good choice if you don’t need to validate the value or add any additional logic.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading