ViewModel 协程 flow 调用Room和网络数据的方式
Posted 黄毛火烧雪下
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了ViewModel 协程 flow 调用Room和网络数据的方式相关的知识,希望对你有一定的参考价值。
ViewModel 调用数据的方式
@Query("SELECT * FROM pocketbook WHERE record_type = :type AND create_time >= :createTimeStart AND create_time <= :createTimeEnd ORDER BY id DESC")
fun getPocketbookListNew(type: String, createTimeStart: Long, createTimeEnd: Long): Flow<List<Pocketbook>>
1.升级前
fun getPockBookListNew(
type: String,
createTimeStart: Long,
createTimeEnd: Long
): Flow<List<Pocketbook>>
val cities = db.gePockBookDao().getPocketbookListNew(type, createTimeStart, createTimeEnd)
return cities.catch e -> e.printStackTrace() .flowOn(Dispatchers.IO)
2.升级后
ViewModel
val loadStateOfPockBookList = MutableLiveData<List<Pocketbook>>()
fun getPockBookListNew1(
type: String,
createTimeStart: Long,
createTimeEnd: Long
) = launch
val cities = db.gePockBookDao().getPocketbookListNew(type, createTimeStart, createTimeEnd)
cities.catch e -> e.printStackTrace() .flowOn(Dispatchers.IO).collect
loadStateOfPockBookList.postValue(it)
Activity
noteBookVM.loadStateOfPockBookList.observe
mAdapter.setNewData(it)
@GET("/marketing/consumer/activities/invite")
suspend fun getInvite(): Response<InviteModel>
val loadStateOfInvite = MutableLiveData<InviteModel>()
fun getInvite1() = launch
flow
var model= activitiesService.getInvite().data
emit(model)
.flowOn(Dispatchers.IO).catch e->e.printStackTrace() .collect
loadStateOfInvite.postValue(it)
以上是关于ViewModel 协程 flow 调用Room和网络数据的方式的主要内容,如果未能解决你的问题,请参考以下文章
Android - ViewModel、LiveData、Room 和 Retrofit 以及协程放在 kotlin 中
Kotlin 协程Flow 异步流 ⑥ ( 调用 Flow#launchIn 函数指定流收集协程 | 通过取消流收集所在的协程取消流 )
Kotlin 协程Flow 异步流 ⑥ ( 调用 Flow#launchIn 函数指定流收集协程 | 通过取消流收集所在的协程取消流 )