当前位置: 首页 > news >正文

Android MVVM+coroutine+retrofit+flow+hilt

文章目录

  • Android MVVM+coroutine+retrofit+flow+hilt
    • 概述
    • 依赖注入层
    • 数据层
    • 视图层
    • 模型视图层
    • 代码下载

Android MVVM+coroutine+retrofit+flow+hilt

概述

在这里插入图片描述

代码结构:

在这里插入图片描述

依赖注入层

数据库:

@Module
@InstallIn(SingletonComponent::class)
class DBModule {@Singleton@Providesfun provideDB(application: Application): AppDatabase {return AppDatabase.getDatabase(application)}@Singleton@Providesfun provideCacheDao(db: AppDatabase): CacheDao {return db.cacheDao()}
}

网络请求:

@Module
@InstallIn(SingletonComponent::class)
class NetworkModule {@Singleton@Providesfun provideOkHttpClient(): OkHttpClient {return HttpManager.okHttpClient}@Singleton@Providesfun provideRetrofit(okHttpClient: OkHttpClient): Retrofit {return HttpManager.retrofit}@Singleton@Providesfun provideLoginApi(retrofit: Retrofit): LoginApi {return retrofit.create(LoginApi::class.java)}@Singleton@Providesfun provideArticleApi(retrofit: Retrofit): ArticleApi {return retrofit.create(ArticleApi::class.java)}
}

数据层

open class BaseModel {@Injectlateinit var cacheHelper: CacheHelperfun <T> requestForResult(block: suspend () -> BaseResponse<T>): Flow<ResultState<T>> {return flow<ResultState<T>> {val response = block()if (response.isSuccessful()) {emit(ResultState.Success(response.data!!))} else {val serverException = ServerException(response.errorCode, response.errorMsg)val e = ExceptionHandler.handleException(serverException)emit(ResultState.Error(e, e.displayMessage))}}.flowOn(Dispatchers.IO).catch {val e = ExceptionHandler.handleException(it)emit(ResultState.Error(e, e.displayMessage))}}suspend fun <T> requestForResult(cacheName: String,cacheBlock: () -> T?,block: suspend () -> BaseResponse<T>): Flow<ResultState<T>> {return flow {val cacheData = cacheBlock()cacheData?.let {emit(ResultState.Success(cacheData, true))}val response = block()if (response.isSuccessful()) {cacheHelper.saveCache(cacheName, response.data!!)emit(ResultState.Success(response.data, false))} else {val serverException = ServerException(response.errorCode, response.errorMsg)val e = ExceptionHandler.handleException(serverException)emit(ResultState.Error(e, e.displayMessage))}}.flowOn(Dispatchers.IO).catch {val e = ExceptionHandler.handleException(it)emit(ResultState.Error(e, e.displayMessage))}}
}
class ArticleModel @Inject constructor() : BaseModel() {@Injectlateinit var articleApi: ArticleApisuspend fun getArticleList(): Flow<ResultState<ArrayList<ArticleBean>>> {val cacheName = "article_list"return requestForResult(cacheName, {cacheHelper.getCache<ArrayList<ArticleBean>>(cacheName, object : TypeToken<ArrayList<ArticleBean>>() {}.type)}, {articleApi.getArticleList()})}
}

视图层

abstract class BaseActivity<VB : ViewBinding> : AppCompatActivity() {private lateinit var _mViewBinding: VBprotected val mViewBinding get() = _mViewBindingoverride fun onCreate(savedInstanceState: Bundle?) {super.onCreate(savedInstanceState)_mViewBinding = createViewBinding()setContentView(_mViewBinding.root)initViews()initData(savedInstanceState)}abstract fun createViewBinding(): VBabstract fun initViews()abstract fun initData(savedInstanceState: Bundle?)
}

@AndroidEntryPoint
class ArticleListActivity : BaseActivity<ActivityArticleListBinding>() {private val mList = arrayListOf<ArticleBean>()private val articleListViewModel by viewModels<ArticleViewModel>()private val progressDialog: ProgressDialog by lazy {ProgressDialog(this).apply {setMessage("加载中")}}override fun createViewBinding(): ActivityArticleListBinding {return ActivityArticleListBinding.inflate(layoutInflater)}override fun initViews() {}override fun initData(savedInstanceState: Bundle?) {mViewBinding.rvArticleList.adapter = ArticleAdapter(this, mList)mViewBinding.btnGetArticleList.setOnClickListener {getArticleList()}observe()}private fun getArticleList() {articleListViewModel.getArticleList()}private fun observe() {lifecycleScope.launch {repeatOnLifecycle(Lifecycle.State.RESUMED) {articleListViewModel.articleFlow.collect {when (it) {is ResultState.Loading -> showLoading()is ResultState.Error -> {showToast(it.message)hideLoading()}is ResultState.Success -> {hideLoading()updateUI(it.data)}}}}}}private fun updateUI(list: ArrayList<ArticleBean>?) {mList.clear()if (list != null) {mList.addAll(list)}mViewBinding.rvArticleList.adapter!!.notifyDataSetChanged()}private fun showLoading() {progressDialog.show()}private fun hideLoading() {progressDialog.hide()}
}

模型视图层

open class BaseViewModel : ViewModel() {fun launchMain(block: suspend CoroutineScope.() -> Unit) {viewModelScope.launch(Dispatchers.Main) {block()}}fun launchIO(block: suspend CoroutineScope.() -> Unit) {viewModelScope.launch(Dispatchers.IO) {block()}}fun launchDefault(block: suspend CoroutineScope.() -> Unit) {viewModelScope.launch(Dispatchers.Default) {block()}}
}
@HiltViewModel
class ArticleViewModel @Inject constructor(private val articleModel: ArticleModel
) : BaseViewModel() {private val _articleFlow =MutableStateFlow<ResultState<ArrayList<ArticleBean>>>(ResultState.None)val articleFlow get() = _articleFlow.asStateFlow()fun getArticleList() {launchIO {articleModel.getArticleList().onStart {_articleFlow.value = ResultState.Loading}.collect {_articleFlow.value = it}}}
}

代码下载

http://www.lryc.cn/news/253514.html

相关文章:

  • elasticsearch副本和分片
  • 【Python】zip
  • 西安安泰——ATA-1220E宽带放大器
  • 数据结构和算法专题---4、限流算法与应用
  • 亚信安慧AntDB受邀分享核心业务系统全域数据库替换实践
  • 1.uniapp基础
  • typescript中的策略模式
  • Hadoop学习笔记(HDP)-Part.16 安装HBase
  • C语言练习记录(蓝桥杯练习)(小蓝数点)
  • RPG项目01_层级设置
  • 相关基础知识
  • 基于单片机的智能健康监测手环的设计
  • boost-字符串处理-判断-查找-裁剪-删除-替换-分割-合并
  • Django 开发 web 后端,好用过 SpringBoot ?
  • 【矩阵】54.螺旋矩阵(顺时针打印矩形元素)
  • 【数据中台】开源项目(5)-Amoro
  • _WorldSpaceLightPos0的含义 UNITY SHADER
  • iOS不越狱自动挂机
  • 智能优化算法应用:基于鼠群算法无线传感器网络(WSN)覆盖优化 - 附代码
  • FL Studio中如何录音的技巧,让你的声音更加出众哦!
  • 前端React基础面试题
  • 【1day】致远A6系统任意文件下载漏洞学习
  • 朝花夕拾华山平台流水账
  • 云原生周刊:K8s 的 YAML 技巧 | 2023.12.4
  • Leetcode.2477 到达首都的最少油耗
  • sizeof()、strlen()、length()、size()的区别(笔记)
  • Redis击穿(热点key失效)
  • 分类预测 | Matlab实现OOA-CNN-SVM鱼鹰算法优化卷积支持向量机分类预测
  • class文件结构
  • 多重背包问题 一句话说清楚“二进制拆分“