如何return 展开里面的收藏?

How to return to launch inside of the collect?

我有一个看起来像这样的方法:

private lateinit var cards: List<Card>

fun start() = viewModelScope.launch {
    if (!::cards.isInitialized) {
        getCards().collect { result ->
            result
                .doIfSuccess {
                    cards = it.data
                    Log.d(TAG, "Received cards")
                }
                .doIfError {
                    _errorState.setIfNotEqual(it.exception)
                    Log.e(TAG, "Cards were not received because of ${it.exception}")
                    return@collect // <--- that's the place
                }
        }
    }

    Log.d(TAG, "Message that needs to be shown only if cards were received")

    if (сards.isEmpty()) {
        Log.e(TAG, "Сards list is empty")
        _errorState.setIfNotEqual(NoCardsException)
        return@launch
    }

    val сard = сards[0]
}

我需要从方法中完全 return,不仅是 .collect 块,我尝试使用 return@launch 或其他一些自定义标签,但它没有即使 Kotlin 编译器建议我这样设置它也无法工作:

我认为您可以使用 transformWhile 创建一个新流程,对您收到的每个项目执行操作,直到您 return 错误。然后收集那个 Flow。我没有测试这个,因为我不太确定你是如何构建 .doIfSuccess.doIfError.

fun start() = viewModelScope.launch {
    if (!::cards.isInitialized) {
        getCards().transformWhile { result ->
            result
                .doIfSuccess {
                    cards = it.data
                    Log.d(TAG, "Received cards")
                }
                .doIfError {
                    _errorState.setIfNotEqual(it.exception)
                    Log.e(TAG, "Cards were not received because of ${it.exception}")
                    return@transformWhile false
                }
            return@transformWhile true
        }.collect()
    }

    //...
}

编辑: 如果您只想要 Flow 中的第一个值,您可以这样做:

fun start() = viewModelScope.launch {
    if (!::cards.isInitialized) {
        getCards().first()
            .doIfSuccess {
                cards = it.data
                Log.d(TAG, "Received cards")
            }
            .doIfError {
                _errorState.setIfNotEqual(it.exception)
                Log.e(TAG, "Cards were not received because of ${it.exception}")
                return@launch
            }
    }

    //...
}