Co Routine Scope

Example code
package gt.kotlin.sandbox.main.threading


import gt.kotlin.sandbox.internal.output.Out
import gt.kotlin.sandbox.internal.output.impl.OutImpl
import kotlinx.coroutines.*
import kotlin.coroutines.CoroutineContext

interface Server {
    fun start()
    fun stop()
}

class ServerImpl(
    private val out: Out,
) : Server, CoroutineScope {

    private val job = Job()

    override val coroutineContext: CoroutineContext
        get() = Dispatchers.Default + job

    override fun start() {
        out.printlnRed("Starting server")

        launch {
            out.printlnBlue("Running server work in thread: ${Thread.currentThread().name}")
            delay(2000)
            out.printlnBlue("Server work completed")
        }

        launch {
            out.printlnGreen("Running additional server work in thread: ${Thread.currentThread().name}")
            delay(1500)
            out.printlnGreen("Additional server work completed")
        }
    }

    override fun stop() {
        out.printlnRed("Stopping server")
        job.cancel()
    }
}


fun main() {
    val out = OutImpl()

    println("--------------------------------------------------------------------------------")
    out.println("Example where there server is aborted prior to finishing:")
    runWithDelayBeforeStopping(1000, out)

    println("--------------------------------------------------------------------------------")
    out.println("Example where the server has time to finish:")
    runWithDelayBeforeStopping(3000, out)
}

private fun runWithDelayBeforeStopping(delayBeforeStopping: Long, out: OutImpl) {
    val server = ServerImpl(out)

    server.start()
    Thread.sleep(delayBeforeStopping)
    server.stop()
}
gt.sandbox.checkout.commit fea718b \
&& cd "${GT_SANDBOX_REPO}"
Cannot re-use scope

https://chatgpt.com/share/31be55da-2e7f-4dc8-9fc3-000384f58086

Sample - 1
import kotlinx.coroutines.*

fun main() = runBlocking {
    val scope = CoroutineScope(Dispatchers.Default)

    val job = scope.launch {
        println("Job started")
        delay(1000)
        println("Job completed")
    }

    delay(500)  // Wait for a while
    scope.cancel()  // Cancel the scope

    // Attempt to launch a new job in the cancelled scope
    val newJob = scope.launch {
        println("New job started")
        delay(1000)
        println("New job completed")
    }

    newJob.invokeOnCompletion { exception ->
        if (exception is CancellationException) {
            println("New job was cancelled due to scope cancellation")
        } else if (exception != null) {
            println("New job completed with exception: $exception")
        } else {
            println("New job completed successfully")
        }
    }

    // Wait for all jobs to complete
    joinAll(job, newJob)
}
Sample - 2
import kotlinx.coroutines.*

fun main() = runBlocking {
    val scope = CoroutineScope(Dispatchers.Default)

    val job = scope.launch {
        println("Job started")
        delay(1000)
        println("Job completed")
    }

    delay(500)  // Wait for a while
    scope.cancel()  // Cancel the scope

    // Create a new scope and launch a new job
    val newScope = CoroutineScope(Dispatchers.Default)
    val newJob = newScope.launch {
        println("New job started")
        delay(1000)
        println("New job completed")
    }

    // Wait for all jobs to complete
    joinAll(job, newJob)
}


Children
  1. Cannot Re Use Scope