Skip to content

Classic API: Transformer

Deprecated

This is the classic API, which is deprecated. It keeps working in 2.x, but new code should use the builder API described in Transformer.

Transformers can also be classes configured with configure { }, using the contracts and data holders described below. This API keeps working, and the two styles mix: every handle exposes its classic contract as handle.contract.

Basic Structure

Use configure { ... } to declare handlers, computations, executions, data holders, and lifecycle callbacks together:

class MyTransformer : Transformer() {
    init {
        configure {
            onSignal<MySignal> { signal ->
                // Handle signal
            }

            onEffect<MyEffect> { effect ->
                // Handle effect
            }

            computation(myComputationContract) {
                // Return computed value
            }

            execution(myExecutionContract) {
                // Run fire-and-forget work
            }
        }
    }
}

For tests and simple local definitions, use the transformer { ... } factory:

val myTransformer = transformer {
    onSignal<MySignal> { signal ->
        send(MyData(signal.value))
    }
}

Older override-based definitions still work, but handlers, computations, and executions replacement DSLs are deprecated in favor of configure.

Constructor Parameters

open class Transformer(
    identity: Contract.Identity = Contract.identity(),
    dispatcher: CoroutineDispatcher = Dispatchers.Default,
    private val capacity: Capacity = Capacity.Default
)
  • identity: Unique identifier for the transformer (auto-generated if not provided)
  • dispatcher: Coroutine dispatcher for processing (defaults to Dispatchers.Default)
  • capacity: Buffer capacity for internal channels

Handlers

Handlers define how your Transformer responds to incoming Signals and Effects.

Signal Handlers

override val handlers: Handlers = handlers {
    onSignal<UserLoginSignal> { signal ->
        // Process the login signal
        val result = authenticateUser(signal.credentials)

        if (result.isSuccess) {
            send(UserData(result.user))
            publish(NavigationEffect.GoToHome)
        } else {
            send(ErrorData("Login failed"))
        }
    }
}

Effect Handlers

override val handlers: Handlers = handlers {
    onEffect<RefreshDataEffect> { effect ->
        // Handle refresh effect
        val freshData = fetchFreshData()
        send(DataRefreshedData(freshData))
    }
}

Communication Scope

Within handler lambdas, you have access to CommunicationScope which provides:

Sending Data

// Send data to the router's data stream
send(UserData(user))

Publishing and Targeting Effects

// Broadcast effect to all matching handlers
publish(LoggingEffect("User logged in"))

// Send effect to a specific transformer identity
send(
    effect = NotificationEffect("Welcome!"),
    identity = notificationTransformerIdentity,
)

Query Other Transformers

// Compute value from another transformer
val userData = compute(userDataContract)

// Compute with arguments
val validationResult = compute(validationContract, inputData)

Execute Operations

// Fire-and-forget execution
execute(cleanupContract)

// Execute with arguments
execute(logContract, "User action performed")

Data Holders

Data Holders provide state management within Transformers:

class UserTransformer : Transformer() {

    // Create a data holder with initial state
    private val userHolder = dataHolder(
        initialValue = UserState(),
        contract = userStateContract
    )

    override val handlers: Handlers = handlers {
        onSignal<UpdateUserSignal> { signal ->
            // Update the held state
            userHolder.update { currentState ->
                currentState.copy(name = signal.newName)
            }

            // The updated state is automatically sent as Data
        }

        onSignal<GetUserSignal> {
            // Access current state
            val currentUser = userHolder.getValue()
            send(CurrentUserData(currentUser))
        }
    }
}

Data Holder Features

  • Automatic Data Publishing: Updates are automatically sent to the data stream
  • Thread-Safe: Updates are synchronized
  • State Tracking: Previous states are tracked for debugging

Creating Data Holders

// Basic data holder
val holder = dataHolder(initialValue = MyState(), contract = myContract)

// Data holder without auto-publishing  
val holder = dataHolder(
    initialValue = MyState(), 
    contract = myContract,
    publishUpdates = false
)

Computations

Computations enable inter-transformer communication for retrieving values:

class CalculatorTransformer : Transformer() {
    init {
        configure {
            computation(currentValueContract) {
                getCurrentCalculatorValue()
            }

            computation(calculateContract) { input: CalculationInput ->
                performCalculation(input)
            }
        }
    }
}

Contract-level caching is enabled when the contract is created, for example Contract.computation<Result>(useCache = true).

Using Computations

override val handlers: Handlers = handlers {
    onSignal<DisplayResultSignal> {
        // Query another transformer's computation
        val currentValue = compute(currentValueContract)
        send(DisplayData(currentValue))
    }

    onSignal<PerformCalculationSignal> { signal ->
        // Query with arguments
        val result = compute(calculateContract, signal.input)
        send(CalculationResultData(result))
    }
}

Executions

Executions are fire-and-forget operations for side effects:

class LoggingTransformer : Transformer() {
    init {
        configure {
            execution(logMessageContract) {
                writeToLogFile("Message logged")
            }

            execution(logWithLevelContract) { logEntry: LogEntry ->
                writeToLogFile(logEntry.level, logEntry.message)
            }
        }
    }
}

Using Executions

override val handlers: Handlers = handlers {
    onSignal<UserActionSignal> { signal ->
        // Fire-and-forget logging
        execute(logMessageContract)

        // With arguments
        execute(logWithLevelContract, LogEntry(LogLevel.INFO, "User action: ${signal.action}"))

        // Continue with main logic
        send(ActionCompletedData(signal.action))
    }
}

Advanced Features

Checkpoint Tracking (Experimental)

Checkpoints enable debugging and flow control:

@OptIn(ExperimentalTransmissionApi::class)
class ComplexTransformer : Transformer() {

    override val handlers: Handlers = handlers {
        onSignal<ProcessDataSignal> { signal ->
            // Pause execution at checkpoint
            val validatedData = pauseOn(validationCheckpoint)

            // Continue processing
            send(ProcessedData(validatedData))
        }

        onEffect<ValidationCompleteEffect> { effect ->
            // Validate checkpoint with result
            validate(validationCheckpoint, effect.validatedData)
        }
    }

    companion object {
        val validationCheckpoint = Contract.checkpointWithArgs<ValidatedData>()
    }
}

Custom Error Handling

class SafeTransformer : Transformer() {
    init {
        configure {
            onError { throwable ->
                // Handle errors that occur in this transformer
                println("Transformer error: ${throwable.message}")
            }

            onSignal<RiskyOperationSignal> { signal ->
                try {
                    val result = riskyOperation(signal.data)
                    send(SuccessData(result))
                } catch (e: Exception) {
                    send(ErrorData(e.message))
                }
            }
        }
    }
}

Lifecycle Management

class ResourceTransformer : Transformer() {

    private val database = openDatabase()

    override fun onCleared() {
        // Cleanup when transformer is cleared
        database.close()
        super.onCleared()
    }
}

Best Practices

1. Single Responsibility

Keep each Transformer focused on a specific domain:

// Good - focused on user authentication
class AuthTransformer : Transformer()

// Good - focused on data caching  
class CacheTransformer : Transformer()

// Avoid - mixed responsibilities
class AuthAndCacheTransformer : Transformer()

2. Immutable State

Use immutable data classes for state:

data class UserState(
    val user: User? = null,
    val isLoading: Boolean = false,
    val error: String? = null
)

3. Error Handling

Handle errors gracefully:

onSignal<LoadDataSignal> { signal ->
    try {
        val data = loadData(signal.id)
        send(DataLoadedData(data))
    } catch (e: Exception) {
        send(ErrorData("Failed to load data: ${e.message}"))
    }
}

4. Use Contracts for Communication

Define contracts for inter-transformer communication:

companion object {
    val userDataContract = Contract.computation<UserData>()
    val validateUserContract = Contract.computationWithArgs<User, Boolean>()
}