【问题标题】:What is the Kotlin equivalent to C# 8's async enumerable?Kotlin 等效于 C# 8 的异步枚举是什么?
【发布时间】:2021-01-24 21:40:51
【问题描述】:

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(); 
}

【问题讨论】:

    标签: kotlin async-await kotlin-coroutines


    【解决方案1】:

    看看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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-01-17
      • 2014-07-12
      • 2010-10-09
      • 1970-01-01
      • 2010-10-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多