首页 > 解决方案 > 使用 Flow 进行多次改造调用

问题描述

我制作了应用程序,用户可以在其中将服务器(回收站行)添加到收藏夹。它只保存IP和端口。比,当用户打开FavoriteFragmentRetrofit 调用每个服务器时

 @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)
        }
    }

一切正常,直到大厅中的收藏服务器不再可用并且改造呼叫失败。我的问题是:如何跳过循环中失败的调用而不使整个函数崩溃。

标签: androidretrofitkotlin-coroutinesflow

解决方案


emitAll如果您希望使用 RxJava 继续像 onResumeNext 这样的流,请发出另一个流

   catch { cause ->
      emitAll(flow { emit(DataState.Errorcause)})
   }

推荐阅读