我创建了这样的实时数据:
val authTokenLiveData: LiveData<String?> = liveData {
emit(accountManager.myAuthToken())
}
我正在观察它:
accountViewModel.authTokenLiveData.observe(this) {
toast("Token is $it")
if(it == null) goToLogin()
}
[起初效果很好,我烘烤了令牌,但是注销后删除令牌,使得令牌为null
,根据观察者,我不应该登录。
[当令牌变为authTokenLiveData
时如何确保null
发出null
,以便观察者允许我进入登录屏幕?
// LiveData object is usually stored within a ViewModel
val currentName: MutableLiveData<String> by lazy {
MutableLiveData<String>()
}
// updating the live data object
// using setValue(T) or postValue(T)
button.setOnClickListener {
val anotherName = "John Doe"
model.currentName.setValue(anotherName)
}
// Observe LiveData Object
// Use the 'by viewModels()' Kotlin property delegate
// from the activity-ktx artifact
private val model: NameViewModel by viewModels()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
// Other code to setup the activity...
// Create the observer which updates the UI.
val nameObserver = Observer<String> { newName ->
// Update the UI, in this case, a TextView.
nameTextView.text = newName
}
// Observe the LiveData, passing in this activity as the LifecycleOwner and the observer.
model.currentName.observe(this, nameObserver)
}
在LiveData
中创建ViewModel
,例如:
val authToken: MutableLiveData<String?> by lazy {
MutableLiveData<String?>()
}
像[[0]一样观察LiveData
:
Activity
像[[0]一样观察viewModel.authToken.observe(viewLifecycleOwner, Observer {
toast("Token is $it")
if(it == null) goToLogin()
})
:
LiveData
将Fragment
传递到viewModel.authToken.observe(viewLifecycleOwner, Observer {
toast("Token is $it")
if(it == null) goToLogin()
})
。然后将数据从ViewModel
发送到AccountManager
,例如:
LiveData
您将获得最新数据到您的观察者区。