withCoroutineScope

fun withCoroutineScope(scope: <Error class: unknown class>): KarlContainerBuilder(source)

Configures the coroutine scope that manages KARL's asynchronous operations.

The coroutine scope is critical for proper lifecycle management and resource cleanup. It controls the execution context for all background operations including learning, data processing, prediction generation, and periodic maintenance tasks.

Scope responsibilities:

  • Background learning: Incremental model training from interaction streams

  • Periodic saves: Automatic state persistence at configurable intervals

  • Data cleanup: Removal of expired interactions and temporary data

  • Health monitoring: Detection and recovery from internal errors

  • Resource management: Proper cleanup when container is shut down

Recommended scope types:

Application-level scope (long-running containers):

val applicationScope = CoroutineScope(
SupervisorJob() + Dispatchers.Default + CoroutineName("KARL-Container")
)

Use for containers that should persist across multiple UI components.

ViewModel scope (UI-bound containers):

class MyViewModel : ViewModel() {
private val container = Karl.forUser(userId)
.withCoroutineScope(viewModelScope)
.build()
}

Use for containers tied to specific UI lifecycles.

Activity/Fragment scope (short-lived containers):

class MyActivity : AppCompatActivity() {
private val activityScope = MainScope()

override fun onDestroy() {
super.onDestroy()
activityScope.cancel()
}
}

Use for containers that should be destroyed with UI components.

Scope configuration best practices:

  • Use SupervisorJob to prevent single task failures from cancelling entire scope

  • Choose appropriate dispatcher based on workload characteristics

  • Include CoroutineName for better debugging and monitoring

  • Ensure scope is cancelled when no longer needed to prevent resource leaks

  • Consider using structured concurrency patterns for complex scenarios

Error handling and recovery:

  • Scope cancellation triggers graceful shutdown of all KARL operations

  • Uncaught exceptions in background tasks are logged but don't crash container

  • Failed operations are retried with exponential backoff when appropriate

  • Container state is automatically saved before scope cancellation

Performance considerations:

  • Learning operations are CPU-intensive and benefit from Dispatchers.Default

  • IO operations use Dispatchers.IO for database and file operations

  • UI updates should use Dispatchers.Main when integrating with UI components

  • Consider using custom dispatchers for fine-grained control over thread pools

Return

This builder instance for method chaining.

Parameters

scope

A properly configured CoroutineScope that will manage all asynchronous operations for the container. The scope should be tied to an appropriate lifecycle and include proper error handling and resource cleanup mechanisms.

See also

CoroutineScope

for scope configuration patterns

kotlinx.coroutines.SupervisorJob

for error isolation strategies

kotlinx.coroutines.Dispatchers

for thread pool selection

Throws

IllegalArgumentException

if scope is null or already cancelled