ฉันใช้ first
ฟังก์ชันจาก kotlin ไหลเวียน. เหตุผลที่ทำไมฉันกำลังใช้นี่ first
ฟังก์ชันคือฉันไม่ต้องเก็บหลังจากเป็นครั้งแรก
ถ้าฉันไม่กลับมามีค่าทางตรรกะมันทำให้ขีดเส้นใต้สีแดงที่ฉันต้องกลับมาเป็นค่าทางตรรกะ. สิ่งที่ฉันควรจะกลับมา? ไม่มีปัญหาตอนที่ฉันเพิ่งกลับมาจริงแต่ฉันอยากรู้ว่ามันหมายถึงอะไร
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
รหัส
/**
* 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
}