Kotlin / kotlinx.coroutines

Library support for Kotlin coroutines
Apache License 2.0
12.96k stars 1.84k forks source link

Add argument to sample to sample at the start of a flow instead of the end? #4217

Open ColtonIdle opened 2 weeks ago

ColtonIdle commented 2 weeks ago

Use case I have a stream of items coming in fairly quickly (30 per second) and according to my PMs I only need to grab the first item, every 5 seconds. This is pretty simple with sample(5.seconds), but I always have to wait at least 5 seconds before I get the first element. It'd be awesome in order to control that I want the element from the beginning of the 5 seconds instead of the last element of the 5 seconds.

The Shape of the API I feel like an argument would suffice, but maybe an enum or something of what type of sampling is being done. Thank you!

JakeWharton commented 2 weeks ago

Sounds a bit like RxJava's throttleLatest. Does that look like what you're asking for?

http://reactivex.io/RxJava/3.x/javadoc/io/reactivex/rxjava3/core/Observable.html#throttleLatest-long-java.util.concurrent.TimeUnit-

ColtonIdle commented 2 weeks ago

That does indeed look like what I'm looking for.

JakeWharton commented 2 weeks ago

Prior to Compose UI (which arguably has this behavior built-in), this operator was used widely between our data sources and UI. Never loved the name, but was just happy to have it built-in to RxJava after a long time evangelizing it. Conceptually I refer to it as the "at-most-every" operator, since you're basically saying notify me as soon as possible but at most every X seconds.

fvasco commented 2 weeks ago

See https://github.com/Kotlin/kotlinx.coroutines/issues/1107#issuecomment-1083076517

ColtonIdle commented 2 weeks ago

@fvasco that looks like a really simple implementation. Much simpler than what sample() is. I'll see if that gets me the behavior I'm looking for. Thanks!