微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何在Kotlin Flow中实现RxJava2的onErrorResumeNext对应物,以返回另一个流?

如何解决如何在Kotlin Flow中实现RxJava2的onErrorResumeNext对应物,以返回另一个流?

我想用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

如果存储库功能是可观察的,那么应该具有什么类似于RxJava onResumeNext的可观察的正确实现?

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

解决方法

发现我可以将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)) })
    }

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。