asProgressionCallback

fun <S, P> SendChannel<P>.asProgressionCallback(closeOnFinish: Boolean = true): ProgressionCallback<S, P>

将一个 SendChannel 作为 ProgressionCallback 使用.

下载文件的使用示例

每当有进度更新, 已下载的字节数都会被发送SendChannel 中. 进度的发送会通过 offer, 而不是通过 send. 意味着 SendChannel 通常要实现缓存.

closeOnFinishtrue, 当下载完成 (无论是失败还是成功) 时会 关闭 SendChannel.

使用示例:

val progress = Channel<Long>(Channel.BUFFERED)

launch {
// 每 3 秒发送一次操作进度百分比
progress.receiveAsFlow().sample(Duration.seconds(3)).collect { bytes ->
group.sendMessage("File upload: ${(bytes.toDouble() / resource.size * 100).toInt() / 100}%.") // 保留 2 位小数
}
}

group.files.uploadNewFile("/foo.txt", resource, callback = progress.asProgressionCallback(true))
group.sendMessage("File uploaded successfully.")

直接使用 ProgressionCallback 也可以实现示例这样的功能, asProgressionCallback 是为了简化操作.