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

com.github.stormbit.vksdk.longpoll.updateshandlers.UpdatesHandler.kt Maven / Gradle / Ivy

The newest version!
package com.github.stormbit.vksdk.longpoll.updateshandlers

import com.github.stormbit.vksdk.events.Event
import kotlinx.coroutines.*
import kotlinx.coroutines.channels.*
import kotlinx.serialization.json.JsonElement
import org.slf4j.LoggerFactory
import java.util.concurrent.ConcurrentHashMap
import kotlin.reflect.KClass

abstract class UpdatesHandler {
    internal val log = LoggerFactory.getLogger(UpdatesHandler::class.java)

    internal var sendTyping = false
    internal val events = ConcurrentHashMap Unit>()

    suspend fun start() {
        eventAllocator = CoroutineScope(Dispatchers.IO).actor {
            for (event in channel) {
                handleCurrentUpdate(event)
            }
        }
    }

    @Suppress("unchecked_cast")
    fun  registerEvent(callback: suspend T.() -> Unit, type: KClass) {
        var parts = Regex("[A-Z][^A-Z]*").findAll(type.simpleName!!).map { it.value.toLowerCase() }.toList()

        if (parts.size != 2) {
            parts = parts.dropLast(1)
        }

        val eventName = parts.joinToString("_")

        events[eventName] = callback as suspend Event.() -> Unit
    }

    private lateinit var eventAllocator: SendChannel

    internal suspend fun send(obj: E) = eventAllocator.send(obj)

    /**
     * Handle one event senderType LongPoll server
     */
    abstract suspend fun handleCurrentUpdate(currentUpdate: E)

    val eventsCount: Int get() = this.events.size
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy