In this paper, the extension of Fragment for ViewMdoel conversion context is mentioned. This paper focuses on the combination of VM and life. The Fragment extension will be covered separately.
Our current development mode has been changed to Activity + Fragment + ViewModel due to jetpack. Why Fragment? Many of you might wonder, why not just use it in your Activity?
As one of the four components of Android, Activity invocation is triggered by the system. Once we intervene, we may cause big bugs. The Fragment’s famous cycle depends on the Activity’s life cycle, and its life cycle functions are all public modified, so we can completely control it. Besides, the transplantation and adaptation of Fragment are relatively strong. Of course, there are other reasons in it.
In the development of Jetpack, ViewMdoel was introduced to solve the problem of data and business entanglements. At the same time, multiple listeners were introduced, which resulted in unmanageable code dispersion. In the sub-background, the Fragment was extended
inline fun <reified T : ViewModel> Fragment.viewModel(
factory: ViewModelProvider.Factory,
body: T. () - >Unit
): T {
val vm = ViewModelProviders.of(this, factory)[T::class.java]
vm.body()
return vm
}
Copy the code
Observe observe in LifecycleExt can simplify class subscriptions and manage them centrally through the context of viewModel transitions in the Fragment
The monitored LifeObserver object is then extended to be used directly in the context of the viewModel in conjunction with LiveData.
fun <T : Any, L : LiveData<T>> LifecycleOwner.observe(liveData: L, body: (T?). ->Unit) =
liveData.observe(this, Observer(body))
Copy the code
Then use the following:
//Fragemnt
onCreare() {
viewModel(viewModelFactory) { // Convert the context to the ViewModel's environment
observe(interceptionPoint, ::initInterceptionConfig)
//globalWindowList LiveData of type and member of ViewModel initGlobalWindowConfig subscription returns data
observe(globalWindowList, ::initGlobalWindowConfig)
observe(quickReplays, ::initQuickReplays)
}
}
Copy the code
With such an extension, the subscriptions in my class will be clear at a glance