知乎专栏 |
定义 MutableLiveData
companion object { val mutableLiveData = MutableLiveData<String>() }
监听 MutableLiveData
mutableLiveData.observe(this) { text -> CoroutineScope(Dispatchers.Main).launch { binding.textViewSentence.text = text } }
发送数据
TestActivity.mutableLiveData.postValue(sentence.result)
import android.os.Bundle import android.widget.TextView import androidx.appcompat.app.AppCompatActivity import androidx.lifecycle.MutableLiveData import androidx.lifecycle.Observer import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.delay import kotlinx.coroutines.launch class KeyValueLiveDataActivity : AppCompatActivity() { // 定义存储 Pair 的 LiveData(Pair<key类型, value类型>) private val keyValueLiveData = MutableLiveData<Pair<String, Int>>() private lateinit var infoTextView: TextView override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_key_value_live_data) infoTextView = findViewById(R.id.tv_info) // 观察键值对数据 observeKeyValueData() // 模拟发送键值对 simulateKeyValueUpdates() } private fun observeKeyValueData() { keyValueLiveData.observe(this) { pair -> // pair 是 Pair 对象,通过 first 取 key,second 取 value val key = pair.first val value = pair.second infoTextView.text = "收到键值对:\nkey=$key, value=$value" } } private fun simulateKeyValueUpdates() { CoroutineScope(Dispatchers.Main).launch { // 发送第一个键值对 delay(1000) keyValueLiveData.value = Pair("北京", 25) // key="北京", value=25 // 发送第二个键值对 delay(3000) keyValueLiveData.value = Pair("上海", 28) // key="上海", value=28 } } }
import android.os.Bundle import android.widget.TextView import androidx.appcompat.app.AppCompatActivity import androidx.lifecycle.MutableLiveData import androidx.lifecycle.Observer import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.delay import kotlinx.coroutines.launch // 自定义数据类,明确存储 "城市"(key)和 "温度"(value) data class CityTemp(val city: String, val temp: Int) class CustomClassLiveDataActivity : AppCompatActivity() { // 定义存储自定义数据类的 LiveData private val cityTempLiveData = MutableLiveData<CityTemp>() private lateinit var infoTextView: TextView override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_key_value_live_data) infoTextView = findViewById(R.id.tv_info) // 观察自定义数据类 observeCityTemp() // 模拟发送数据 simulateDataUpdates() } private fun observeCityTemp() { cityTempLiveData.observe(this) { cityTemp -> // 直接通过属性名访问 key 和 value,语义更清晰 infoTextView.text = "城市:${cityTemp.city}\n温度:${cityTemp.temp}℃" } } private fun simulateDataUpdates() { CoroutineScope(Dispatchers.Main).launch { delay(1000) cityTempLiveData.value = CityTemp("北京", 25) // 传递 key 和 value delay(3000) cityTempLiveData.value = CityTemp("上海", 28) } } }