All Downloads are FREE. Search and download functionalities are using the official Maven repository.

ru.astrainteractive.astralibs.async.AsyncComponent.kt Maven / Gradle / Ivy

There is a newer version: 3.14.1
Show newest version
package ru.astrainteractive.astralibs.async

import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.cancel
import java.io.Closeable
import java.util.*
import java.util.concurrent.ConcurrentLinkedQueue
import kotlin.coroutines.AbstractCoroutineContextElement
import kotlin.coroutines.CoroutineContext

/**
 * If you're familiar with AndroidViewModel - this is similar
 *
 * This component has [CoroutineScope] inside so you can use it as ViewModel's and etc
 */
abstract class AsyncComponent : Closeable, CoroutineScope, AbstractCoroutineContextElement(AsyncComponent), Runnable {
    override val coroutineContext: CoroutineContext = SupervisorJob() + Dispatchers.IO
    val componentScope: CoroutineScope
        get() = this
    var queue: Queue = ConcurrentLinkedQueue()
    override fun run() {
        queue.poll()?.run()
    }

    override fun close() {
        coroutineContext.cancel()
    }

    companion object Key : CoroutineContext.Key

    /**
     * Default implementation of [AsyncComponent]
     */
    class Default : AsyncComponent()
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy