Aar*_*n B 3 async-await kotlin 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();
}
Run Code Online (Sandbox Code Playgroud)
看一下Asynchronous Flow,它似乎是最接近的等效项。
类似的例子是:
fun main() = runBlocking {
seconds().take(10).collect {
println(it)
}
}
fun seconds() = flow<Instant> {
while (true) {
delay(1000L)
emit(Instant.now())
}
}
Run Code Online (Sandbox Code Playgroud)
我使用的是1.3.9kotlinx-coroutines-core版本
| 归档时间: |
|
| 查看次数: |
579 次 |
| 最近记录: |