kotlin协程flow任务意外结束未emit数据retryWhen onEmpty(5)

kotlin协程flow任务意外结束未emit数据retryWhen onEmpty(5)

import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.*
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.withTimeoutOrNull

fun main(args: Array<String>) {
    val MSG = "fly_error"

    runBlocking {
        load().onStart {
            println("---")
            println("onStart")
        }.onEach {
            if (it == null) {
                throw Exception(MSG)
            } else {
                println("获取数据 $it")
            }
        }.retryWhen { cause, attempt ->
            println("${cause.message}")
            println("retry ${attempt}")
            delay(100) //延时重试

            attempt < 3  //重试3次
        }.catch {
            it.printStackTrace() //如果重试3次仍失败,此次将抛出异常打印错误栈
        }.onCompletion {
            println("onCompletion")
        }.onEmpty {
            // flow完成但没有发射任何元素。
            // 可用onEmpty发射一些默认的空态值。
            println("onEmpty")

            emit("empty")
        }.collect {
            println("collect $it")
        }
    }
}

fun load() = flow {
    var time = 1000L

    withTimeoutOrNull(time) {
        //生成一个概率布尔,模拟加载概率性成功/失败
        var b = Boolean.let {
            var p: Int = (Math.random() * 100).toInt() % 2
            when (p) {
                0 -> true
                1 -> false
                else -> false
            }
        }

        var s: String? = null
        if (b) {
            println("加载成功")
            s = "fly"
        } else {
            println("加载失败")
        }

        delay(time + 1) //模拟超时

        emit(s)
    }
}

---
onStart
加载失败
onCompletion
onEmpty
collect empty

kotlin协程flow retry功能函数返回失败后重试(4)_zhangphil的博客-CSDN博客一、flow ,emit,onCompletion,collect。kotlin协程flow retryWhen当功能函数加载失败后重试(3)_zhangphil的博客-CSDN博客。kotlin协程flow retryWhen当功能函数加载失败后重试(3)加载一次失败,重试1次成功。kotlin协程flow retry retryWhen(2)_zhangphil的博客-CSDN博客。kotlin协程flow retry retryWhen(2)二、retryWhen。初次加载失败,重试两次成功。https://blog.csdn.net/zhangphil/article/details/130093111kotlin协程flow retryWhen当功能函数加载失败后重试(3)_zhangphil的博客-CSDN博客kotlin协程flow retryWhen当功能函数加载失败后重试(3)加载一次失败,重试1次成功。https://blog.csdn.net/zhangphil/article/details/130092299

kotlin协程flow retry retryWhen(2)_zhangphil的博客-CSDN博客kotlin协程flow retry retryWhen(2)二、retryWhen。https://blog.csdn.net/zhangphil/article/details/130086523

kotlin协程flow filter map flowOn zip combine(1)_zhangphil的博客-CSDN博客一、flow ,emit,onCompletion,collect。四、map,重组改写数据。八、conflate 合并。九、debounce去重。二、函数作为flow。https://blog.csdn.net/zhangphil/article/details/130084723

猜你喜欢

转载自blog.csdn.net/zhangphil/article/details/130115220
今日推荐