mirror of
https://github.com/InsanusMokrassar/TelegramBotAPI.git
synced 2026-11-07 12:23:14 +00:00
improve drafts flows
This commit is contained in:
1 parent
b734757062
commit
14402f9283
4 files changed
+71
-8
No files matched your search
@@ -0,0 +1,25 @@
|
||||
package dev.inmo.tgbotapi.utils
|
||||
|
||||
import dev.inmo.tgbotapi.types.DraftId
|
||||
import kotlinx.coroutines.NonCancellable.isActive
|
||||
import kotlinx.coroutines.sync.Mutex
|
||||
import kotlinx.coroutines.sync.withLock
|
||||
import kotlin.random.Random
|
||||
|
||||
class DraftIdAllocator {
|
||||
val allocated = mutableSetOf<DraftId>()
|
||||
val mutex = Mutex()
|
||||
|
||||
suspend fun allocate(): DraftId = mutex.withLock {
|
||||
while (isActive) {
|
||||
val draftId = DraftId(Random.nextLong())
|
||||
if (allocated.add(draftId)) {
|
||||
return draftId
|
||||
}
|
||||
}
|
||||
error("Unable to allocate a unique draft ID")
|
||||
}
|
||||
suspend fun free(draftId: DraftId) = mutex.withLock {
|
||||
allocated.remove(draftId)
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user