Home > front end >  What should I have to return at kotlin Flow first function?
What should I have to return at kotlin Flow first function?

Time:11-24

I am using first function from kotlin flow. The reason why I'm using this first function is that I don't have to collect after the first time. If I don't return any boolean value, it makes red underline that I have to return a boolean value. What should I return? There aren't any problem when I just return true, but I want to know what it means.

    private fun getGroupNameData() {
        viewModelScope.launch {
            repository.loadGroupsWithFlow()
                .buffer()
                .first { newList ->
                    groupData.clear()
                    newList.forEach { newGroupData ->
                        groupData[newGroupData.id] = newGroupData.name
                    }
                    true // <- what is this boolean value?
                }
        }
    }

first Code.

/**
 * The terminal operator that returns the first element emitted by the flow matching the given [predicate] and then cancels flow's collection.
 * Throws [NoSuchElementException] if the flow has not contained elements matching the [predicate].
 */
public suspend fun <T> Flow<T>.first(predicate: suspend (T) -> Boolean): T {
    var result: Any? = NULL
    collectWhile {
        if (predicate(it)) {
            result = it
            false
        } else {
            true
        }
    }
    if (result === NULL) throw NoSuchElementException("Expected at least one element matching the predicate $predicate")
    return result as T
}

CodePudding user response:

This overload of Flow.first() is used to get the first value of flow which matches the given predicate. That's why the lambda expects you to return a boolean at the end. For whichever value the lambda returns true, that value will be returned and flow will be cancelled.

If you only need the first value, you should the other overload which doesn't accept a predicate lambda.

val newList = repository.loadGroupsWithFlow().buffer().first() // Use this first()
groupData.clear()
newList.forEach { newGroupData ->
    groupData[newGroupData.id] = newGroupData.name
}

Btw I don't think buffer is required. You can remove that.

  • Related