Advertisement
Ein_gruenes_Beb

ChannelManager.kt

Aug 1st, 2023
102
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Kotlin 1.03 KB | Source Code | 0 0
  1. package io.github.eingruenesbeb.secommandchangelogbot.managers
  2.  
  3. import kotlinx.coroutines.channels.Channel
  4.  
  5. object ChannelManager {
  6.     // A map to store channels indexed by their IDs
  7.     private val channelMap = mutableMapOf<String, Channel<*>>()
  8.  
  9.     // Initialize a channel of a specific type with a given ID
  10.     fun <T> initializeChannel(id: String, capacity: Int = Channel.RENDEZVOUS): Channel<T> {
  11.         if (channelMap.containsKey(id)) {
  12.             throw IllegalArgumentException("Channel with ID $id already exists.")
  13.         }
  14.  
  15.         val channel = Channel<T>(capacity)
  16.         channelMap[id] = channel
  17.         return channel
  18.     }
  19.  
  20.     // Retrieve a channel of a specific type using its ID
  21.     @Suppress("UNCHECKED_CAST")
  22.     fun <T> getChannel(id: String): Channel<T>? {
  23.         return channelMap[id] as? Channel<T>
  24.     }
  25.  
  26.     // Close a channel of a specific type using its ID
  27.     fun closeChannel(id: String) {
  28.         val channel = channelMap[id]
  29.         channel?.close()
  30.         channelMap.remove(id)
  31.     }
  32. }
  33.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement