Home > Enterprise >  Mutability/Immutability state variables in viewmodel
Mutability/Immutability state variables in viewmodel

Time:12-03

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.

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.

CodePudding user response:

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.

  • Related