or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

channels.mdcoroutine-builders.mdcoroutine-management.mddispatchers.mderror-handling.mdflow-api.mdindex.mdselect-expression.mdsynchronization.md

coroutine-management.mddocs/

0

# Coroutine Management

1

2

Core lifecycle management for coroutines including Job interface, scoping, and structured concurrency support. This provides the foundation for all coroutine operations with automatic cleanup and cancellation propagation.

3

4

## Capabilities

5

6

### Job Interface

7

8

The fundamental interface for managing coroutine lifecycle with structured concurrency support.

9

10

```kotlin { .api }

11

/**

12

* A background job that represents a coroutine

13

*/

14

interface Job : CoroutineContext.Element {

15

/** Returns true when the job is active */

16

val isActive: Boolean

17

/** Returns true when the job has completed */

18

val isCompleted: Boolean

19

/** Returns true when the job was cancelled */

20

val isCancelled: Boolean

21

/** All direct children of this job */

22

val children: Sequence<Job>

23

/** Parent job of this job */

24

val parent: Job?

25

26

/** Start the job if it was created with CoroutineStart.LAZY */

27

fun start(): Boolean

28

/** Cancel the job with optional cause */

29

fun cancel(cause: CancellationException? = null)

30

/** Wait for the job to complete */

31

suspend fun join()

32

/** Install completion handler */

33

fun invokeOnCompletion(handler: CompletionHandler): DisposableHandle

34

}

35

36

/**

37

* A job that can be completed manually

38

*/

39

interface CompletableJob : Job {

40

/** Complete the job successfully */

41

fun complete(): Boolean

42

/** Complete the job with exception */

43

fun completeExceptionally(exception: Throwable): Boolean

44

}

45

46

/**

47

* Factory function to create a Job

48

*/

49

fun Job(parent: Job? = null): CompletableJob

50

51

/**

52

* Factory function to create a supervisor job

53

*/

54

fun SupervisorJob(parent: Job? = null): CompletableJob

55

```

56

57

**Usage Examples:**

58

59

```kotlin

60

import kotlinx.coroutines.*

61

62

// Create a job manually

63

val job = Job()

64

65

// Create a supervisor job (failures don't cancel siblings)

66

val supervisorJob = SupervisorJob()

67

68

// Launch a child job

69

val childJob = CoroutineScope(job).launch {

70

delay(1000)

71

println("Child completed")

72

}

73

74

// Cancel parent (cancels all children)

75

job.cancel()

76

77

// Wait for completion

78

childJob.join()

79

```

80

81

### Deferred Interface

82

83

Job with result value for computations that produce results asynchronously.

84

85

```kotlin { .api }

86

/**

87

* A Job that produces a result value

88

*/

89

interface Deferred<out T> : Job {

90

/** Wait for completion and return the result */

91

suspend fun await(): T

92

/** Get completed result or throw if not completed */

93

fun getCompleted(): T

94

/** Get completion exception or null if completed successfully */

95

fun getCompletionExceptionOrNull(): Throwable?

96

}

97

98

/**

99

* A Deferred that can be completed manually

100

*/

101

interface CompletableDeferred<T> : Deferred<T>, CompletableJob {

102

/** Complete with a value */

103

fun complete(value: T): Boolean

104

}

105

106

/**

107

* Factory function to create CompletableDeferred

108

*/

109

fun <T> CompletableDeferred(parent: Job? = null): CompletableDeferred<T>

110

```

111

112

**Usage Examples:**

113

114

```kotlin

115

import kotlinx.coroutines.*

116

117

// Create a CompletableDeferred

118

val deferred = CompletableDeferred<String>()

119

120

// Complete it from another coroutine

121

launch {

122

delay(100)

123

deferred.complete("Hello, World!")

124

}

125

126

// Await the result

127

val result = deferred.await()

128

println(result) // "Hello, World!"

129

```

130

131

### CoroutineScope Interface

132

133

Defines a scope for new coroutines with structured concurrency and automatic cancellation.

134

135

```kotlin { .api }

136

/**

137

* Defines a scope for new coroutines

138

*/

139

interface CoroutineScope {

140

/** The context of this scope */

141

val coroutineContext: CoroutineContext

142

}

143

144

/**

145

* Factory function to create a CoroutineScope

146

*/

147

fun CoroutineScope(context: CoroutineContext): CoroutineScope

148

149

/**

150

* Creates a MainScope for UI applications

151

*/

152

fun MainScope(): CoroutineScope

153

154

/**

155

* Global scope for top-level coroutines (use with caution)

156

*/

157

object GlobalScope : CoroutineScope

158

```

159

160

**Extension Properties and Functions:**

161

162

```kotlin { .api }

163

/**

164

* Returns true if the scope is active

165

*/

166

val CoroutineScope.isActive: Boolean

167

168

/**

169

* Cancels the scope and all its children

170

*/

171

fun CoroutineScope.cancel(cause: CancellationException? = null)

172

173

/**

174

* Ensures the scope is active or throws CancellationException

175

*/

176

fun CoroutineScope.ensureActive()

177

```

178

179

**Usage Examples:**

180

181

```kotlin

182

import kotlinx.coroutines.*

183

184

// Create a scope with specific context

185

val scope = CoroutineScope(Dispatchers.Default + SupervisorJob())

186

187

// Launch coroutines in the scope

188

scope.launch {

189

// This coroutine will be cancelled when scope is cancelled

190

delay(1000)

191

println("Coroutine completed")

192

}

193

194

// Check if scope is active

195

if (scope.isActive) {

196

println("Scope is still active")

197

}

198

199

// Cancel the entire scope

200

scope.cancel()

201

```

202

203

### Scoping Functions

204

205

Functions that create child scopes with structured concurrency.

206

207

```kotlin { .api }

208

/**

209

* Creates a child scope and waits for all children to complete

210

*/

211

suspend fun <R> coroutineScope(block: suspend CoroutineScope.() -> R): R

212

213

/**

214

* Creates a supervisor scope where child failures don't affect siblings

215

*/

216

suspend fun <R> supervisorScope(block: suspend CoroutineScope.() -> R): R

217

218

/**

219

* Returns the current coroutine context

220

*/

221

suspend fun currentCoroutineContext(): CoroutineContext

222

```

223

224

**Usage Examples:**

225

226

```kotlin

227

import kotlinx.coroutines.*

228

229

suspend fun parallelWork() = coroutineScope {

230

// All launched coroutines are children of this scope

231

val deferred1 = async { computeValue1() }

232

val deferred2 = async { computeValue2() }

233

234

// If any child fails, all siblings are cancelled

235

val result1 = deferred1.await()

236

val result2 = deferred2.await()

237

238

result1 + result2

239

} // Function doesn't complete until all children complete

240

241

suspend fun supervisedWork() = supervisorScope {

242

// Child failures don't cancel siblings

243

val job1 = launch { riskyOperation1() }

244

val job2 = launch { riskyOperation2() }

245

246

// Both jobs run independently

247

joinAll(job1, job2)

248

}

249

```

250

251

### Completion Handlers

252

253

```kotlin { .api }

254

/**

255

* Handler for job completion

256

*/

257

typealias CompletionHandler = (cause: Throwable?) -> Unit

258

259

/**

260

* Handle for disposing completion handlers

261

*/

262

interface DisposableHandle {

263

/** Dispose the handle */

264

fun dispose()

265

}

266

```

267

268

### Context Elements

269

270

Core context elements for coroutine configuration.

271

272

```kotlin { .api }

273

/**

274

* Debugging name for coroutines

275

*/

276

data class CoroutineName(val name: String) : CoroutineContext.Element {

277

companion object Key : CoroutineContext.Key<CoroutineName>

278

}

279

280

/**

281

* Non-cancellable context for cleanup operations

282

*/

283

object NonCancellable : CoroutineContext.Element, Job {

284

override val isActive: Boolean get() = true

285

override val isCompleted: Boolean get() = false

286

override val isCancelled: Boolean get() = false

287

// ... other Job methods that are no-ops

288

}

289

```

290

291

**Usage Examples:**

292

293

```kotlin

294

import kotlinx.coroutines.*

295

296

// Name coroutines for debugging

297

launch(CoroutineName("background-task")) {

298

// This coroutine will appear as "background-task" in debugging

299

delay(1000)

300

}

301

302

// Use NonCancellable for cleanup

303

try {

304

riskyOperation()

305

} finally {

306

withContext(NonCancellable) {

307

// This cleanup code won't be cancelled

308

cleanupResources()

309

}

310

}

311

```

312

313

## Job Hierarchy and Cancellation

314

315

The Job interface establishes parent-child relationships that form a hierarchy:

316

317

1. **Parent-Child Relationship**: When a Job is used as a parent context for launching coroutines, those coroutines become children

318

2. **Cancellation Propagation**: Cancelling a parent job cancels all its children

319

3. **Completion Waiting**: A parent job waits for all children to complete before completing itself

320

4. **Exception Propagation**: By default, child exceptions cancel the parent and all siblings

321

322

This hierarchy ensures structured concurrency where resource cleanup and cancellation are handled automatically.