let's say I have a `suspend fun sum(): Long` insid...
# coroutines
j
let's say I have a
suspend fun sum(): Long
inside which I have a reference to something with the method
suspend fun consume(consumer: suspend (Long) -> Unit)
. The implementation is the obvious thing:
Copy code
var sum = 0L
numbers.consume { sum += it }
return sum
Now let's say I want to specify a maximum number of numbers. How can I cause the
numbers.consume
to stop pushing numbers at me once that max is hit?
e
The obvious thing is by throwing an exception, but that should be only used for exceptional circumstances. If you want to support that kind of limit for normal operations, then you should plan for that in your
consumer
signature, e.g. define it as
consumer: suspend (Long) -> Boolean
where the resulting boolean indicates whether consumer is ready to accept more.