Skip to content

Commit

Permalink
Introduce application coroutine scope
Browse files Browse the repository at this point in the history
  • Loading branch information
Sergey Mashkov committed Oct 19, 2018
1 parent 975674c commit 0bb718a
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 3 deletions.
Original file line number Diff line number Diff line change
@@ -1,15 +1,24 @@
package io.ktor.application

import kotlinx.coroutines.*

/**
* Represents configured and running web application, capable of handling requests
* Represents configured and running web application, capable of handling requests.
* It is also the application coroutine scope that is cancelled immediately at application stop so useful
* for launching background coroutines.
*
* @param environment Instance of [ApplicationEnvironment] describing environment this application runs in
*/
class Application(val environment: ApplicationEnvironment) : ApplicationCallPipeline() {
class Application(val environment: ApplicationEnvironment) : ApplicationCallPipeline(), CoroutineScope {
private val applicationJob = SupervisorJob(environment.parentCoroutineContext[Job])

override val coroutineContext = environment.parentCoroutineContext + applicationJob

/**
* Called by [ApplicationEngine] when [Application] is terminated
*/
fun dispose() {
applicationJob.cancel()
uninstallAllFeatures()
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,6 @@ import kotlinx.coroutines.io.*
import kotlinx.coroutines.io.jvm.javaio.*
import kotlinx.io.core.*
import kotlinx.io.streams.*
import org.junit.Test
import org.junit.runners.model.*
import org.slf4j.*
import java.io.*
Expand All @@ -34,6 +33,7 @@ import java.util.zip.*
import kotlin.concurrent.*
import kotlin.coroutines.*
import kotlin.test.*
import kotlin.test.Test

@Suppress("KDocMissingDocumentation")
abstract class EngineTestSuite<TEngine : ApplicationEngine, TConfiguration : ApplicationEngine.Configuration>(
Expand Down Expand Up @@ -1674,6 +1674,21 @@ abstract class EngineTestSuite<TEngine : ApplicationEngine, TConfiguration : App
}
}

@Test
fun testApplicationScopeCancellation() {
var job: Job? = null

createAndStartServer {
job = application.launch {
delay(10000000L)
}
}

server!!.stop(1, 10, TimeUnit.SECONDS)
assertNotNull(job)
assertTrue { job!!.isCancelled }
}

private fun String.urlPath() = replace("\\", "/")
private class ExpectedException(message: String) : RuntimeException(message)

Expand Down

0 comments on commit 0bb718a

Please sign in to comment.