kotlin - Kotlin 中与 C# 8 的异步枚举等效的是什么?

标签 kotlin async-await kotlin-coroutines

C# 8 现在有 IAsyncEnumerable 。有与此等效的 Kotlin 吗?例如,在 C# 中,您现在可以 await foreach(...)(使用 IAsyncEnumerable):

async Task Main()
{
    await foreach(var dt in new Seconds().Take(10))
    {
        Console.WriteLine(dt);
    }
}

public class Seconds : IAsyncEnumerable<DateTime>
{
    public class FooEnumerator : IAsyncEnumerator<DateTime>
    {
        public DateTime Current { get; set; }
        public async ValueTask DisposeAsync() {}
        public async ValueTask<bool> MoveNextAsync()
        {
            await Task.Delay(1000);
            Current = DateTime.Now;
            return true;
        }
    }

    public IAsyncEnumerator<DateTime> GetAsyncEnumerator(CancellationToken cancellationToken = default)
        => new FooEnumerator(); 
}

最佳答案

看看Asynchronous Flow ,这似乎是最接近的等价物。

类似的例子是:

fun main() = runBlocking {
    seconds().take(10).collect {
        println(it)
    }
}

fun seconds() = flow<Instant> {
    while (true) {
        delay(1000L)
        emit(Instant.now())
    }
}

我正在使用kotlinx-coroutines-core版本1.3.9

关于kotlin - Kotlin 中与 C# 8 的异步枚举等效的是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64286283/

相关文章:

java - 如何在 Kotlin 中创建和重用包?

concurrency - Rust 异步等待 : check if any future in a list resolves to true concurrently?

javascript - React 中的 Axios 用于存储响应以供将来使用

kotlin - withContext 和 suspendCancellableCoroutine 之间的区别

Kotlin 协同例程按顺序执行,但仅在生产机器上执行

kotlin - kotlin 中 == 和 === 有什么区别

android - 为什么我无法在 jetpack compose 中通过 firebase 使用移动身份验证?

c# - 如何在 mvvmcross View 模型中使用异步?

android - 如何使用 kotlin 流程中的 flatMapMerge?

java - 与 Room 的多对多关系导致错误 : Entities and Pojos must have a usable public constructor