Last active
November 24, 2021 22:39
-
-
Save MarinaShaposhnikova/bcec5338814b93ecd6681877cb29bb7e to your computer and use it in GitHub Desktop.
Throttle Coroutines
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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