在 Google 代码实验室 "Load and display images from the Internet" 中,有一个很好且非常优雅的 MutableLiveData 示例。
大纲:
- 您使用 LiveData(内部)和 MutableLiveData(外部)制作了一个 ViewModel
- 现在您可以直接在视图、片段或活动中使用数据
好处是这些数据是生命周期感知的,您可以将返回的值用于观察者。
class OverviewViewModel : ViewModel() {
enum class MarsApiStatus { LOADING, ERROR, DONE }
private val _status = MutableLiveData<MarsApiStatus>()
val status: LiveData<MarsApiStatus> = _status
private val _photos = MutableLiveData<List<MarsPhoto>>()
val photos: LiveData<List<MarsPhoto>> = _photos
/**
* Call getMarsPhotos() on init so we can display status immediately.
*/
init {
getMarsPhotos()
}
/**
* Gets Mars photos information from the Mars API Retrofit service and updates the
* [MarsPhoto] [List] [LiveData].
*/
private fun getMarsPhotos() {
viewModelScope.launch {
_status.value = MarsApiStatus.LOADING
Log.d(TAG, "loading")
try {
_photos.value = MarsApi.retrofitService.getPhotos()
_status.value = MarsApiStatus.DONE
Log.d(TAG, "done")
} catch (e: Exception) {
_status.value = MarsApiStatus.ERROR
_photos.value = listOf()
Log.d(TAG, "error")
}
}
}
}
您可以通过观察它们或直接在这样的视图中使用它们来使用状态或照片值:
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/photos_grid"
android:layout_width="0dp"
android:layout_height="0dp"
app:layoutManager="androidx.recyclerview.widget.GridLayoutManager"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:listData="@{viewModel.photos}"
app:spanCount="2"
tools:itemCount="16"
tools:listitem="@layout/grid_view_item" />
...在您“注册”并连接 f.ex 中的所有内容之后。关于片段,像这样:
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
try {
val binding = FragmentOverviewBinding.inflate(inflater)
//val binding = GridViewItemBinding.inflate(inflater)
// Allows Data Binding to Observe LiveData with the lifecycle of this Fragment
binding.lifecycleOwner = this
// Giving the binding access to the OverviewViewModel
binding.viewModel = viewModel
binding.photosGrid.adapter = PhotoGridAdapter()
return binding.root
} catch (e: Exception) {
Log.e("OverviewFragment", "${e.localizedMessage}")
}
return null
}