LiveData is a responsive programming component provided by Jetpack. It can contain any type of data and notify observers when the data changes. In other words, we can wrap the data using LiveData, and then observe it in the Activity, and then we can actively notify the Activity of data changes.
1. Simple use
class MainViewModel(countReserved:Int) : ViewModel() { /*When the counter variable is called externally, what is actually obtained is an instance of _counter, but data cannot be set for the counter, thus ensuring the encapsulation of the ViewModel's data. */ val counter:LiveData<Int> get()=_counter private val _counter = MutableLiveData<Int>() init{ _counter.value=countReserved } fun plusOne() { val count = _counter.value ?: 0 _counter.value = count + 1 } fun clear() { _counter.value = 0 } }
class MainActivity : AppCompatActivity() { … override fun onCreate(savedInstanceState: Bundle?) { … { () } { () } (this, Observer { count -> = () // Update the latest data to the interface }) } }
and switchMap
In order to be able to cope with various demand scenarios, LiveData provides two conversion methods: map() and switchMap() methods.
The purpose of the map() method is to convert LiveData that actually contains the data and LiveData that is only used to observe the data.
For example, there is a User class that contains the user's name and age
data class User(var firstName:String,var lastName:String,var age:Int)
The map() method can freely transform the User type LiveData into any other type LiveData.
class MainViewModel(countReserved:Int) : ViewModel() { private val userLiveData = MutableLiveData<User>() val userName:LiveData<String>=(userLiveData){user-> "${} ${}" } }
If another method is obtained when a LiveData object in the ViewModel is called, then we can use the switchMap() method to convert this LiveData object into another observable LiveData object.
Create a new Repository singleton class
object Repository{ fun getUser(userId:String):LiveData<User>{ val liveData=MutableLiveData<User>() =User(userId,userId,0) return liveData } }
class MainViewModel(countReserved:Int) : ViewModel() { private val userLiveData = MutableLiveData<User>() val user:LiveData<User>=(userIdLiveData){userId-> (userId) } fun getUser(userId:String){ =userId } }
This is the end of this article about writing LiveData components tutorials in Android development using Kotlin. For more related Android LiveData content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!