android - 使用 Flow 进行多次改造调用
问题描述
我制作了应用程序,用户可以在其中将服务器(回收站行)添加到收藏夹。它只保存IP和端口。比,当用户打开FavoriteFragment
Retrofit 调用每个服务器时
@GET("v0/server/{ip}/{port}")
suspend fun getServer(
@Path("ip") ip: String,
@Path("port") port: Int
): Server
因此,在repository
我混合来源并进行多次调用时:
suspend fun getFavoriteServersToRecyclerView(): Flow<DataState<List<Server>>> = flow {
emit(DataState.Loading)
try {
val getFavoritesServersNotLiveData = favoritesDao.getFavoritesServersNotLiveData()
val list: MutableList<Server> = mutableListOf()
getFavoritesServersNotLiveData.forEach { fav ->
val server = soldatApiService.getServer(fav.ip, fav.port)
list.add(server)
}
emit(DataState.Success(list))
} catch (e: Exception) {
emit(DataState.Error(e))
}
}
然后在ViewModel
我创建LiveData
对象
fun getFavoriteServers() {
viewModelScope.launch {
repository.getFavoriteServersToRecyclerView()
.onEach { dataState ->
_favoriteServers.value = dataState
}.launchIn(viewModelScope)
}
}
一切正常,直到大厅中的收藏服务器不再可用并且改造呼叫失败。我的问题是:如何跳过循环中失败的调用而不使整个函数崩溃。
解决方案
emitAll
如果您希望使用 RxJava 继续像 onResumeNext 这样的流,请发出另一个流
catch { cause ->
emitAll(flow { emit(DataState.Errorcause)})
}
推荐阅读
- .net-core - AutoMapper:在 Net Core 2 语法中双向映射
- javascript - 在图片下设置按钮
- angular - 可在 Ngfor 内部观察到
- python - Pandas HDFStore 更改存储数据帧的格式
- r - 我想计算 R 中数据帧的每一行中每个值/字符的出现次数,包括当它被其他值/字符包围时
- google-apps-script - 在特定日期从单元格中查找值,然后无限期保留该值
- javascript - 使用 phabricator API 使用 javascript 创建 maniphest 任务
- opengl - 片段着色器中的“不正确的预处理器指令”?
- c# - 有更好的方法吗?
- datatables - 这个javascript语句做了什么样的赋值:var api = this.api(), data;