Kotlin+MVVM+Retrofit+協程+ViewBinding+EventBus

MVVM

https://github.com/baiyuliang/MVVM

Kotlin+MVVM+Retrofit+協程+ViewBinding+EventBus

注意:使用ViewBinding需要AndroidStudio版本爲4.0+

項目框架整體架構圖:

架構圖

本框架的特點:

1.使用Kotlin語言

2.使用MVVM+協程開發模式,相較於常用的MVP+RXJava開發模式,會減省大量的MvpView的創建,以及大量的接口回調,並且不再需要Presenter的註冊和註銷,減少內存泄漏風險

3.ViewBinding將會使你不再需要進行findViewById的繁瑣工作,比ButterKinfer更加方便

4.關於消息傳遞,github有LiveData改造的LiveDataBus,作用及使用方法都類似於EventBus,而本項目選擇繼續使用EventBus的原因,則是因爲EventBus的穩定性和靈活性

Example

編寫Activity:

class TestActivity : BaseActivity<BaseViewModel, ActivityTestBinding>() {


    override fun initView() {

    }

    override fun initClick() {
     
    }

    override fun initData() {

    }

    override fun initVM() {

    }

}

Fragment同!

列表adapter:

class ArticleListAdapter(context: Activity, listDatas: ArrayList<ArticleBean>) :
    BaseAdapter<ItemArticleBinding, ArticleBean>(context, listDatas) {

    override fun convert(holder: BaseViewHolder, t: ArticleBean, position: Int) {
        val v = holder.v as ItemArticleBinding
        Glide.with(mContext).load(t.envelopePic).into(v.ivCover)
        v.tvTitle.text = t.title
        v.tvDes.text = t.desc
    }

}

調用接口(ViewModel):

class MainViewModel : BaseViewModel() {

    var articlesData = MutableLiveData<ArticleListBean>()

    fun getArticleList(page: Int, isShowLoading: Boolean) {
        launch({ httpUtil.getArticleList(page) }, articlesData, isShowLoading)
    }

}

在Activity或Fragment中直接用vm.getArticleList()即可

消息傳遞:

本項目中,像EventBus的註冊與註銷,以及消息接收全部放在了BaseActivity中,並提供了一個對外的消息處理方法,利用消息Code來區分不同消息,在需要使用消息的界面,重寫該方法即可:

發送消息:App.post(EventMessage(EventCode.REFRESH))

    /**
     * 接收消息
     */
    override fun handleEvent(msg: EventMessage) {
        super.handleEvent(msg)
        if (msg.code == EventCode.REFRESH) {
            ToastUtil.showToast(mContext, "主頁:刷新")
            page = 0
            vm.getArticleList(page,false)
        }
    }

這樣做的好處就是

1:不在需要你去手動在每個界面去註冊和註銷EventBus,你只用關心什麼時候post消息,和什麼時間接受消息即可,大大減少出錯機率,並提高代碼可讀性;

2:可以隨時更換消息傳遞框架,方便快捷;

當然,缺點就是發送一個消息,所有界面都會收到,個人認爲利大於弊,且弊可以忽略

該框架已應用到自己公司項目中,運行良好,如果後續發現有坑的地方,會及時更新!

https://github.com/baiyuliang/MVVM

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章