gpt4 book ai didi

list - 如何从非流函数获取流输出

转载 作者:行者123 更新时间:2023-12-02 01:27:50 25 4
gpt4 key购买 nike

我想要来自非流函数(返回类型 Flow<T> )的流输出(返回类型 T )。

fun getTotalFiles(): Int 
// Say, This is a library function it'll return the number of files (Int) in that folder at that specific moment.

//And,
fun getAllFiles(): List<File>
// Say, This is a library function it'll return all the files (List<File>) in that folder.

该文件夹中的文件将来可能并且将会更改。

现在,我想不断观察输出,那么我该如何实现呢?

fun getFlowOfTotalFiles(): Flow<Int> =
// A wrapper function that converts the library function return type to an observable flow, Flow<Int>

//And,
fun getFlowOfAllFiles(): Flow<List<File>> =
// A wrapper function that converts the library function return type to an observable flow, Flow<List<File>>

最佳答案

为了专门监视目录中的文件,您可以使用 WatchService 并使用 flow 构建器将其转换为流。像这样的事情:

fun getDirectoryMonitorFlow(directory: String) = flow {
FileSystems.getDefault().newWatchService().use { watchService ->
while (true) {
val watchKey = Path.of(directory).register(watchService, ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY)
if (watchKey.pollEvents().isNotEmpty()) {
emit(Unit)
}
yield() // give flow opportunity to be cancelled.
if (!watchKey.reset()) {
println("Directory became unreadable. Finishing flow.")
break
}
}
}
}
.catch { println("Exception while monitoring directory.") }
.flowOn(Dispatchers.IO)

然后你的类可能看起来像:

fun getFlowOfTotalFiles(): Flow<Int> = getFlowOfAllFiles()
.map { it.size }
.distinctUntilChanged()

fun getFlowOfAllFiles(): Flow<List<File>> = flow {
emit(Unit) // so current state is always emitted
emitAll(getDirectoryMonitorFlow(directory))
}
.map {
File(directory).listFiles()?.toList().orEmpty()
}
.flowOn(Dispatchers.IO)
.distinctUntilChanged()

尽管您可能会考虑将第一个流设为私有(private) SharedFlow,这样您就不会运行多个 WatchService 来同时监视同一目录。

关于list - 如何从非流函数获取流输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74030384/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com