# android-网络请求框架 **Repository Path**: rojims/network-request-framework ## Basic Information - **Project Name**: android-网络请求框架 - **Description**: 安卓Kotlin+MVVM+Retrofit+协程+ViewBinding+EventBus快速快发框架 - **Primary Language**: Kotlin - **License**: Not specified - **Default Branch**: master - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 6 - **Forks**: 1 - **Created**: 2022-04-13 - **Last Updated**: 2023-10-26 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README # MVVM Kotlin+MVVM+Retrofit+协程+ViewBinding+EventBus 注意:使用ViewBinding需要AndroidStudio版本为4.0+ 项目框架整体架构图: ![架构图](https://img-blog.csdnimg.cn/20200601152544441.png) ## 本框架的特点: 1.使用Kotlin语言 2.使用MVVM+协程开发模式,相较于常用的MVP+RXJava开发模式,会减省大量的MvpView的创建及大量的接口回调,并且不再需要Presenter的注册和注销,减少内存泄漏风险 3.ViewBinding(根据xml自动生成),你将不再需要进行findViewById的繁琐工作,比ButterKinfer更加方便 4.关于消息传递,github上有基于LiveData的LiveEventBus(https://github.com/JeremyLiao/LiveEventBus),优点是具有生命周期感知能力,不需要主动注册和注销,但缺点是书写相对麻烦,且无法统一配置,衍生版SmartEventBus虽然支持定制,但配置依然麻烦,而本项目选择继续使用EventBus的原因,则是因为EventBus的强大以及它的稳定性和灵活性,且方便统一配置(下面有讲到); ## Example ## 编写Activity(只需要传入对应的ViewModel和ViewBinding即可): class TestActivity : BaseActivity() { } Fragment同! ## 编写Adapter(只需要传入数据model类型和item的ViewBinding即可): class ArticleListAdapter(context: Activity, listDatas: ArrayList) : BaseAdapter(context, listDatas) { override fun convert(v: ItemArticleBinding, t: ArticleBean, position: Int) { Glide.with(mContext).load(t.envelopePic).into(v.ivCover) v.tvTitle.text = t.title v.tvDes.text = t.desc } } ## 添加接口(ApiService): @GET("test") suspend fun test(@QueryMap options: HashMap): BaseResult 注意:suspend不可缺少! ## 创建ViewModel: class MainViewModel : BaseViewModel() { var articlesData = MutableLiveData() fun getArticleList(page: Int, isShowLoading: Boolean) { launch({ httpUtil.getArticleList(page) }, articlesData, isShowLoading) } } ## 调用接口: 在Activity或Fragment中直接通过传入的ViewModel调用: vm.getArticleList()//调用接口 vm.articlesData.observe(this, Observer {//返回结果 }) ## 消息传递: 本项目中,像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:可以随时更换消息传递框架,方便快捷; 当然,缺点,只有一个,就是发送消息所有活动界面都会收到,但这个所谓的缺点其实完全可以忽略! 该框架已应用到自己公司项目中,运行良好,如果后续发现有坑的地方,会及时更新!