Reputation: 1041
C# 8 now has IAsyncEnumerable. Is there a Kotlin equivalent to this? For instance, in C# you can await foreach(...)
now (with 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();
}
Upvotes: 3
Views: 759
Reputation: 147911
Take a look at the Asynchronous Flow, which seems to be the closest equivalent.
A similar example would be:
fun main() = runBlocking {
seconds().take(10).collect {
println(it)
}
}
fun seconds() = flow<Instant> {
while (true) {
delay(1000L)
emit(Instant.now())
}
}
I'm using kotlinx-coroutines-core
version 1.3.9
Upvotes: 5