美文网首页
Android 抽取ViewBinding和ViewModel

Android 抽取ViewBinding和ViewModel

作者: Gxinyu | 来源:发表于2022-04-26 17:17 被阅读0次

    前言

      最近根据项目需要抽取了一套针对MVVM模式的BaseActivity和BaseFragment,使View与ViewModel不再需要在每个Activity或者Fragment不需要单独创建,目前属于比较简单的版本,直接把代码放下面。

    View层

    abstract class BaseFragment<ViewModelLazy : ViewModel, Binding : ViewBinding> : Fragment() {
    
        protected lateinit var binding: Binding
        protected var viewModel: ViewModelLazy? = null
    
        override fun onCreateView(
            inflater: LayoutInflater,
            container: ViewGroup?,
            savedInstanceState: Bundle?,
        ): View? {
            viewModel = bindViewModel()
            binding = bindViewBinding()
            bindObserver()
            loadData()
            return binding.root
        }
    
        /**
         * 监听数据变化
         */
        open fun bindObserver() {
    
        }
    
        /**
         * 加载数据
         */
        open fun loadData() {
    
        }
    
        /**
         * 绑定ViewModel
         * @return ViewModelLazy
         */
        open fun bindViewModel(): ViewModelLazy? {
            return null
        }
    
        /**
         * 绑定布局
         * @return View
         */
        abstract fun bindViewBinding(): Binding
    
    }
    

    ViewModel

    class MainViewModel : ViewModel() {
    
        private val _loginResult = MutableLiveData<Boolean>()
        val loginResult: LiveData<Boolean> = _loginResult
    
        fun login(name: String, pwd: String) {
            viewModelScope.launch(Dispatchers.IO) {
                //网络请求
                _loginResult.postValue(true)
            }
        }
    }
    

    ViewModelEx

    //扩展BaseActivity的ViewModel
    @MainThread
    public inline fun <reified VM : ViewModel> BaseActivity<*, *>.createViewModel(
        noinline ownerProducer: () -> ViewModelStoreOwner = { this },
        noinline factoryProducer: (() -> ViewModelProvider.Factory)? = null,
    ): Lazy<VM> = createViewModelLazy(VM::class, { ownerProducer().viewModelStore }, factoryProducer)
    
    @MainThread
    public fun <VM : ViewModel> BaseActivity<*, *>.createViewModelLazy(
        viewModelClass: KClass<VM>,
        storeProducer: () -> ViewModelStore,
        factoryProducer: (() -> ViewModelProvider.Factory)? = null,
    ): Lazy<VM> {
        val factoryPromise = factoryProducer ?: {
            defaultViewModelProviderFactory
        }
        return ViewModelLazy(viewModelClass, storeProducer, factoryPromise)
    }
    
    
    //扩展BaseFragment的ViewModel
    @MainThread
    public inline fun <reified VM : ViewModel> BaseFragment<*, *>.createFragmentViewModel(
        noinline ownerProducer: () -> ViewModelStoreOwner = { this },
        noinline factoryProducer: (() -> ViewModelProvider.Factory)? = null,
    ): Lazy<VM> = createFragmentViewModelLazy(VM::class, { ownerProducer().viewModelStore }, factoryProducer)
    
    @MainThread
    public fun <VM : ViewModel> BaseFragment<*, *>.createFragmentViewModelLazy(
        viewModelClass: KClass<VM>,
        storeProducer: () -> ViewModelStore,
        factoryProducer: (() -> ViewModelProvider.Factory)? = null,
    ): Lazy<VM> {
        val factoryPromise = factoryProducer ?: {
            defaultViewModelProviderFactory
        }
        return ViewModelLazy(viewModelClass, storeProducer, factoryPromise)
    }
    

    具体实现

    class MainFragment : BaseFragment<MainViewModel, FragmentMainBinding>() {
    
        override fun bindViewModel(): MainViewModel {
            return createFragmentViewModel<MainViewModel>().value
        }
    
        override fun bindViewBinding(): FragmentMainBinding {
            return FragmentMainBinding.inflate(layoutInflater)
        }
    
        override fun loadData() {
            super.loadData()
            viewModel?.login("gxy", "123456")
        }
    
        override fun bindObserver() {
            super.bindObserver()
            viewModel?.loginResult?.observe(viewLifecycleOwner) {
                Log.e("TAG", "bindObserver:登录结果${it} ")
            }
        }
    }
    

    相关文章

      网友评论

          本文标题:Android 抽取ViewBinding和ViewModel

          本文链接:https://www.haomeiwen.com/subject/tuhhyrtx.html