Skip to content

Coroutines

Miu edited this page Aug 15, 2023 · 2 revisions

Nexus internally uses native Java threads (system threads) to process its different tasks using its own thread pool, this can be costly especially when there is another perfect alternative existing. Kotlin sports its own coroutine system that is available only to Kotlin, which we do not use by default to keep interoperability with Java developers, but we still want Kotlin developers to utilize this amazing technology, so we added our own async wrapper.

Nexus Launch

Launch is our own async wrapper designed to enable developers to wrap Nexus' internal async (such as event handling, etc.) with their own cheaper or better alternatives, you can configure Nexus to use a different async method by changing its configuration (note, we use GlobalScope for this example, it's recommended to use your own CoroutineScope for this):

Nexus.configure {
    launch.launcher = NexusLaunchWrapper { task ->
        GlobalScope.launch { task.run() }
    }
    
    launch.scheduler = NexusScheduledLaunchWrapper { timeInMillis, task ->
        return@NexusScheduledLaunchWrapper object : Cancellable {
            val job = GlobalScope.launch {
                delay(timeInMillis)
                task.run()
            }
    
            override fun cancel(mayInterruptIfRunning: Boolean): Boolean {
                job.cancel()
                return true
            }
        }
    }
}

Performance-wise, this doesn't bring any big or noticeable of an impact, but if you feel that it does, feel free to implement a solution such as this and see how it goes. Although, it also does not bring any harm to implement this solution.

To get started with Nexus, we recommend reading the following in chronological:

  1. Installation & Preparing Nexus
  2. Designing Commands
  3. Command Interceptors
  4. Additional Features (Subcommand Router, Option Validation)
  5. Context Menus
  6. Command Synchronization

You may want to read a specific part of handling command and middleware responses:

You can also read about additional features of Nexus:

You can read about synchronizing commands to Discord:

For more additional performance:

Additional configurations:

Clone this wiki locally