Kotlin 扩展函数之Fragment扩展(与ViewMdoel,LifecycleOwner订阅)

1,870 阅读1分钟

之前Kotlin 扩展函数之Boolean扩展中介绍了Kotlin 扩展函数及用途,并简单的扩展了基本数据类型Boolean类,在次文中提到了Fragment对于ViewMdoel转换上下文的扩展,此文注重vm、life的结合,Fragment后续扩展会单独再介绍。

一般我们目前的开发模式由于jetpack的接入而变成了Activity + Fragment + ViewModel的模式,为什么会用Fragment呢?可能很多人都有疑问,为何不直接在Activity中使用?

Activity 作为Android的四大组件,调用过程都是由系统触发的,我们一旦干预就可能造成很大的bug,Fragment的成名周期依赖与Activity的生命周期,并且生命周期函数都是public 修饰的,所以我们完全可控,且Fragment的移植性、适配性比较强,当然还有其他的原因在里面。

在jetpack开发中ViewMdoel的引入解决了数据和业务的结偶,同时也入了多个监听导致代码分散不好管理,在次背景下对Fragment进行扩展

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
}

通过viewModel 转换期在Fragment中的上下文关系,配合LifecycleExt 中的observe 可以简洁类中的订阅关系,集中管理

然后将被监控的LifeObserver 对象进行扩展,使之与LiveData 结合起来 直接能在viewModel的上下文中使用。

fun <T : Any, L : LiveData<T>> LifecycleOwner.observe(liveData: L, body: (T?) -> Unit) =
    liveData.observe(this, Observer(body))

然后使用的如下:

//Fragemnt
onCreare() {
viewModel(viewModelFactory) { // 转换上下文 变成ViewModel 的环境
    observe(interceptionPoint, ::initInterceptionConfig)
    //globalWindowList LiveData类型并是ViewModel的成员变量 initGlobalWindowConfig订阅返回数据
    observe(globalWindowList, ::initGlobalWindowConfig)
    observe(quickReplays, ::initQuickReplays)
 }
 }
 

经过这样一个扩展,我的类中订阅关系将会一目了然