Skip to content

Instantly share code, notes, and snippets.

@MarinaShaposhnikova
Last active November 24, 2021 22:39
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save MarinaShaposhnikova/bcec5338814b93ecd6681877cb29bb7e to your computer and use it in GitHub Desktop.
Save MarinaShaposhnikova/bcec5338814b93ecd6681877cb29bb7e to your computer and use it in GitHub Desktop.
Throttle Coroutines
package com.meier.marina.magiccoroutines
import android.util.Log
import kotlinx.coroutines.experimental.*
import kotlinx.coroutines.experimental.android.UI
import kotlinx.coroutines.experimental.channels.*
import kotlin.coroutines.experimental.CoroutineContext
class ViewModel {
private var count = 0
val channel: SendChannel<Int>
init {
channel = Channel()
launch(UI) {
channel.throttle().consumeEach { "received value: $it".logD() }
}
}
fun useThrottle() {
launch {
count++
"sent value: $count".logD()
channel.send(count)
}
}
fun <T> Channel<T>.throttle(
wait: Long = 1500,
context: CoroutineContext = DefaultDispatcher
): ReceiveChannel<T> = produce(context) {
var mostRecent: T
consumeEach {
mostRecent = it
delay(wait)
while (!isEmpty) {
mostRecent = receive()
}
send(mostRecent)
}
}
}
const val LOG_TAG = "marina_meier"
fun Any?.logD() = Log.d(LOG_TAG, this?.toString() ?: "")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment