2

我想实现最后离线的方法Flow,如果失败,首先尝试从远程源获取数据,例如改造抛出网络异常,我想使用下面的代码从本地源获取数据

    return flow { emit(repository.fetchEntitiesFromRemote()) }
        .map {

            println(" getPostFlowOfflineLast() First map in thread: ${Thread.currentThread().name}")

            val data = if (it.isEmpty()) {
                repository.getPostEntitiesFromLocal()
            } else {
                repository.deletePostEntities()
                repository.savePostEntity(it)
                repository.getPostEntitiesFromLocal()
            }

            entityToPostMapper.map(data)
        }
        .catch { cause ->
            println("❌ getPostFlowOfflineLast() FIRST catch with error: $cause, in thread: ${Thread.currentThread().name}")
           flow { emit(repository.getPostEntitiesFromLocal()) }
        }
        .map { postList ->

            println(" getPostFlowOfflineLast() Second map in thread: ${Thread.currentThread().name}")

            ViewState<List<Post>>(
                status = Status.SUCCESS,
                data = postList
            )
        }
        .catch { cause: Throwable ->

            println("❌ getPostFlowOfflineLast() SECOND catch with error: $cause, in thread: ${Thread.currentThread().name}")

            flow {
                emit(
                    ViewState<List<Post>>(
                        Status.ERROR,
                        error = cause
                    )
                )
            }
        }

但它被异常卡住了

I: ❌ getPostFlowOfflineLast() FIRST catch with error: java.net.UnknownHostException: Unable to resolve host "jsonplaceholder.typicode.com": No address associated with hostname, in thread: main

onResumeNext如果存储库函数是 Observerable ,那么像 RxJava 一样拥有任何 observable 的正确实现应该是什么?

onErrorResumeNext { _: Throwable ->
     Observable.just(repository.getPostEntitiesFromLocal())
}
4

1 回答 1

0

发现我可以使用emitAll流来继续流甚至多次。

    .catch { cause ->
        println("❌ getPostFlowOfflineLast() FIRST catch with error: $cause, in thread: ${Thread.currentThread().name}")
        emitAll(flow { emit(repository.getPostEntitiesFromLocal()) })
    }
    .map {
        if (!it.isNullOrEmpty()) {
            entityToPostMapper.map(it)
        } else {
            throw EmptyDataException("No data is available!")
        }
    }
    .map { postList ->
        println(" getPostFlowOfflineLast() Third map in thread: ${Thread.currentThread().name}")
        ViewState(status = Status.SUCCESS, data = postList)
    }
    .catch { cause: Throwable ->
        println("❌ getPostFlowOfflineLast() SECOND catch with error: $cause, in thread: ${Thread.currentThread().name}")
        emitAll(flow { emit(ViewState(Status.ERROR, error = cause)) })
    }
于 2020-08-16T09:37:34.423 回答