Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import kotlinx.coroutines.*
- import kotlinx.coroutines.sync.Mutex
- import kotlinx.coroutines.sync.withLock
- import java.util.*
- import kotlin.coroutines.CoroutineContext
- import kotlin.random.Random
- val random = Random(Date().time)
- suspend fun slowRequest(): Long {
- delay(3000)
- return random.nextLong(0, 1000)
- }
- class Manager(
- private val context: CoroutineContext
- ) {
- private var state: Deferred<Long>? = null
- private val mutex = Mutex()
- private val list: MutableList<Deferred<Long>> = mutableListOf()
- private suspend fun startSlowRequest() = coroutineScope {
- if (state == null) {
- state = async {
- val result = slowRequest()
- launch(context) { clear() }
- result
- }
- }
- }
- private suspend fun clear() = coroutineScope {
- mutex.withLock {
- list.forEach { it.join() }
- list.clear()
- state = null
- }
- }
- suspend fun slow(): Long = coroutineScope {
- mutex.withLock {
- startSlowRequest()
- val invocation = async { state!!.await() }
- list.add(invocation)
- invocation
- }.await()
- }
- }
- fun main() = runBlocking {
- val manager = Manager(coroutineContext)
- repeat(23) {
- launch { println(manager.slow()) }
- delay(500)
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment