Android開發(fā)中用Kotlin編寫LiveData組件教程
LiveData是Jetpack提供的一種響應(yīng)式編程組件,它可以包含任何類型的數(shù)據(jù),并在數(shù)據(jù)發(fā)生變化的時(shí)候通知給觀察者。也就是說,我們可以將數(shù)據(jù)使用LiveData來包裝,然后在Activity中去觀察它,就可以主動將數(shù)據(jù)變化通知給Activity了。
1.簡單使用
class MainViewModel(countReserved:Int) : ViewModel() {
/*當(dāng)外部調(diào)用counter變量時(shí),實(shí)際上獲得的就是_counter的實(shí)例,但是無法給counter設(shè)置數(shù)據(jù),從而保證了ViewModel的數(shù)據(jù)的封裝性。*/
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?) {
…
plusOneBtn.setOnClickListener {
viewModel.plusOne()
}
clearBtn.setOnClickListener {
viewModel.clear()
}
viewModel.counter.observe(this, Observer { count ->
infoText.text = count.toString() // 將最新數(shù)據(jù)更新到界面上
})
}
}2.map和switchMap
LiveData為了能夠應(yīng)對各種不同的需求場景,提供了兩種轉(zhuǎn)換方法:map()和switchMap()方法。
map()方法的作用就是將實(shí)際包含數(shù)據(jù)的LiveData和僅用于觀察數(shù)據(jù)的LiveData進(jìn)行轉(zhuǎn)換。
比如說有一個(gè)User類,User中包含用戶的姓名和年齡
data class User(var firstName:String,var lastName:String,var age:Int)
map()方法可以將User類型的LiveData自由地轉(zhuǎn)型成任意其他類型地LiveData。
class MainViewModel(countReserved:Int) : ViewModel() {
private val userLiveData = MutableLiveData<User>()
val userName:LiveData<String>=Transformations.map(userLiveData){user->
"${user.firstName} ${user.lastName}"
}
}如果ViewModel中的某個(gè)LiveData對象時(shí)調(diào)用另外的方法獲取的,那么我們就可以借助switchMap()方法,將這個(gè)LiveData對象轉(zhuǎn)換成另一個(gè)可觀察的LiveData對象。
新建Repository單例類
object Repository{
fun getUser(userId:String):LiveData<User>{
val liveData=MutableLiveData<User>()
liveData.value=User(userId,userId,0)
return liveData
}
}class MainViewModel(countReserved:Int) : ViewModel() {
private val userLiveData = MutableLiveData<User>()
val user:LiveData<User>=Transformations.SwitchMap(userIdLiveData){userId->
Repository.getUser(userId)
}
fun getUser(userId:String){
userIdLiveData.value=userId
}
}到此這篇關(guān)于Android開發(fā)中用Kotlin編寫LiveData組件教程的文章就介紹到這了,更多相關(guān)Android LiveData內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Android Handler的postDelayed()關(guān)閉的方法及遇到問題
這篇文章主要介紹了Android Handler的postDelayed()關(guān)閉的方法,本文給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2021-04-04
Android開發(fā)之Fragment懶加載的幾種方式及性能對比
這篇文章主要介紹了Android開發(fā)之Fragment懶加載的幾種方式及性能對比的相關(guān)資料,具體詳細(xì)介紹需要的小伙伴可以參考下面文章內(nèi)容2022-05-05
Android自定義View中attrs.xml的實(shí)例詳解
這篇文章主要介紹了Android自定義View中attrs.xml的實(shí)例詳解的相關(guān)資料,在自定義View首先對attrs.xml進(jìn)行布局的實(shí)現(xiàn)及屬性的應(yīng)用,需要的朋友可以參考下2017-07-07

