commonMain.love.forte.simbot.common.collection.flows.kt Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of simbot-common-collection Show documentation
Show all versions of simbot-common-collection Show documentation
Simple Robot,一个通用的bot风格事件调度框架,以灵活的统一标准来编写bot应用。
/*
* Copyright (c) 2024. ForteScarlet.
*
* Project https://github.com/simple-robot/simpler-robot
* Email [email protected]
*
* This file is part of the Simple Robot Library.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* Lesser GNU General Public License for more details.
*
* You should have received a copy of the Lesser GNU General Public License
* along with this program. If not, see .
*
*/
package love.forte.simbot.common.collection
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.channels.ChannelIterator
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.produceIn
/**
* Converts a [Flow] into an [Iterator] by providing custom implementations for the `hasNext` and `next` functions.
*
* @param producerScope The [CoroutineScope] that the produced [Flow] will be associated with.
* @param hasNext A lambda expression that returns `true` if there are more elements in the [Flow], or `false` otherwise.
* @param next A lambda expression that returns the next element in the [Flow].
* @return An [Iterator] that can be used to iterate over the elements in the [Flow].
*/
public inline fun Flow.asIterator(
producerScope: CoroutineScope,
crossinline hasNext: ChannelIterator.() -> Boolean,
crossinline next: ChannelIterator.() -> T
): Iterator {
val iterator = produceIn(producerScope).iterator()
return iterator {
while (hasNext(iterator)) {
val nextValue = next(iterator)
yield(nextValue)
}
}
}