Skip to content
7 min readUpdated 28 Oct 2026

Core

reaktor-core is the module every other Reaktor module imports. It holds four things: Feature slots, which let shared code ask for a platform service without checking which platform it runs on; Capability, a marker for resources that must be closed; Adapter, a weak handle through which shared code drives a platform controller; and a few primitives for time, dispatchers, logging, atomics and JSON. Core does nothing a higher layer could do instead: it does no dependency injection and knows nothing about the graph.

Overview#

How reaktor-core connects shared code to each platform. Platform start-up code fills Feature slots. Shared code reads a slot once, at the edge of the app, and passes the object on through graph ports. An Adapter gives shared code a weak handle on a platform controller, and a Capability is a resource that closes once.PLATFORM START-UP FILLS SLOTSAndroidFeature.Database = sqlDelightDatabase()BaseActivity.connect(adapters)iOSfills the slots it supportsin its app start-up codeBrowser and WorkersKotlin/JS fills its ownstorage, auth and work slotsJVM: Hangar and serversfill theirs in main()FEATURE: ONE SLOT REGISTRYvar Feature.Database by CreateSlot<…>()a module declares a slot; about 21 existAuthDatabaseSqlCameraWorkThemeLocationStorageAnalyticsTelemetryDependency…A slot reads null until something fills it.Like any service locator, a missing slotfails where it is read, not at start-up.fillSHARED CODERead once, at the edgeat start-up or in a platform adapter;graph nodes get it through portsAdapter<Controller>a WeakRef to an Activity, aUIViewController or a browser global;a call returns null once it is goneCapabilityAtomicCapability.close() runs once;cancel the scope and it closesread
How core connects shared code to each platform. Graph nodes never read slots themselves; they get what they need through ports.

Read the picture from left to right. Each platform's start-up code installs the services it can provide, shared code picks each one up once at the edge of the app, and from there the graph hands it to the nodes that need it. Core holds only these hand-off points. Everything that decides how an app is wired lives a layer up.

What it contains#

PieceWhereNotes
Feature slot registry and CreateSlot<T>framework/Feature.ktAbout 21 slots, used by BestBuds and most Reaktor modules
Capability and AtomicCapabilitycapabilities/Capability.ktclose() runs once, guarded by an atomic compare-and-set
Adapter<Controller>framework/Adapter.ktHolds the controller through a WeakRef
WeakRef, AtomicInt, ConcurrentHashMapframework/Expectations.kt, structs/expect/actual per target; WeakRef on JS keeps a strong reference
epochTime(), Dispatch, Kermit logging, atomicfuutils/, framework/Dispatch.ktThin wrappers over the kotlinx libraries
JSON defaultsframework/Json.ktencodeDefaults, ignoreUnknownKeys, classDiscriminator = "type"
Platform codesrc/{android,ios,jvm,js}MainAndroid registers adapters with BaseActivity.connect(...)

Paths are under reaktor-core/src/commonMain/kotlin/dev/shibasis/reaktor/core/.

Feature slots#

A module declares a slot, the platform start-up code fills it, and shared code reads it:

var Feature.Database by CreateSlot<ObjectDatabase>()

Feature.Database = sqlDelightDatabase()
val database = Feature.Database

Feature is a process-wide map from an integer slot id to the installed object, with lock-free reads and writes. A slot reads as null until something fills it, and setting it to null empties it again, which lets a test or a shutting-down shell remove what it installed. The slots in use include Auth, Database, Sql, GraphQl, Camera, Gallery, the speech recogniser and synthesiser, GooglePubSub, Work, Theme, Location, Compression, File, Permission, Storage, Analytics, Crashlytics, Telemetry and Dependency.

A slot registry is a service locator, with a service locator's cost: a missing registration fails when it is used, not at start-up. So read a slot at the edge of the app, at start-up or in a platform adapter, and pass the object on from there. Graph nodes get their collaborators through ports, never through Feature. Dependency injection belongs to Koin, reached through the Feature.Dependency slot.

Capability: a resource to close#

interface Capability : AutoCloseable

abstract class AtomicCapability : Capability {
    private val closed = atomic(false)
    final override fun close() {
        if (closed.compareAndSet(expect = false, update = true)) doClose()
    }
    protected abstract fun doClose()
}

Holding a Capability means owning its lifecycle, nothing more. Closing twice is safe. The owner of a coroutine scope owns the cleanup of what runs in it: cancel the job and its resources close, and use { } closes on an exception too.

The word "capability" means different things across Reaktor, and none of them is a security token:

InCapability means
reaktor-coreA resource that must be closed
reaktor-graph, reaktor-graph-portA behaviour a node composes, such as LifecycleCapability, DependencyScopeCapability or PortCapability
The capability runtime designWhat the device or network can do right now, as a tier

None of them grants authority, so read Reaktor's "capability" as one of these, not as the object-capability security model.

Adapter: a weak platform handle#

open class Adapter<Controller>(controller: Controller) : Component {
    val ref: WeakRef<Controller> = WeakRef(controller)
    val controller: Controller? get() = ref.get()

    operator fun <R> invoke(fn: Controller.() -> R?): R?
    suspend fun <R> suspended(fn: suspend Controller.() -> R?): R?
    open fun handle(event: ControllerEvent) { }
}

Shared code drives an Android activity, an iOS view controller or a browser global through an adapter, without owning it or keeping it alive. A call returns null when the controller is gone, and invokeResult and suspendedResult return a Result instead. PermissionAdapter, StorageAdapter, CameraAdapter and AuthAdapter subclass it to do the platform work.

Adapters are registered by hand: on Android, BaseActivity.connect(listOf(permissionAdapter, …)) ties them to the activity's lifecycle, and a forgotten registration fails when the adapter is first used. The iOS BaseController is a stub.

Primitives#

  • Time: epochTime() over kotlinx-datetime's system clock.
  • Dispatchers: Dispatch.Main, Dispatch.IO and Dispatch.Default, with Dispatchers.Async chosen per platform: IO on Android, iOS and the JVM, Default on JS.
  • Logging: a thin wrapper over Kermit.
  • Atomics and maps: kotlinx-atomicfu, and a lock-free ConcurrentHashMap written for Reaktor because JS and Kotlin/Native have no shared one. It is slower than java.util.concurrent's, and portable.
  • JSON: kotlinx.serialization with encodeDefaults = true, ignoreUnknownKeys = true and classDiscriminator = "type", which every sealed hierarchy in the framework relies on. The global json is a mutable variable: read it anywhere, but do not reconfigure it while other code runs.

Device tiers: a design#

A capability runtime would extend Feature from "which implementation runs here" to "at what quality, right now". It is designed and not built. It would install through one more slot:

var Feature.Capability by CreateSlot<CapabilityRuntime>()

interface CapabilityRuntime : AutoCloseable {
    val environment: StateFlow<EnvironmentSnapshot>
    suspend fun resolve(request: CapabilityRequest): CapabilityDecision
}

Collectors, written as adapters, would read raw platform signals. A normaliser would fold them into one EnvironmentSnapshot of tiers: PerformanceClass, MemoryClass, NetworkQuality, NetworkCost, ThermalClass, PowerMode and FormFactor. A strategy selector would then choose an implementation by tier and policy, and record why.

Product code would branch on tiers, never on a raw model string, vendor ID, user-agent string or hardware score. The platforms already push the same way: browsers reduce the user agent and round deviceMemory to a power of two, Android computes a Media Performance Class, and iOS exposes thermal state and low-power mode for the app to bucket itself. An unknown signal resolves to the most conservative tier, so the default code path is the one that works on the weakest device. Nothing enforces this yet; the web code still reads a raw user agent.

What core improves#

Usual approachWhat goes wrongCore's approach
An expect/actual pair for every platform serviceEvery service needs an actual on every target, and expect class is still Beta in KotlinOne Feature slot per service: shared code reads an interface, and each platform's start-up code installs its own implementation
Shared code that holds an Android activity or an iOS view controllerThe shared object keeps the screen alive after the platform has destroyed it, and memory leaksAn Adapter holds the controller through a weak reference, and a call returns null once the controller is gone
A hand-written "closed" flag on each resourceClosing twice, or from two threads at once, runs the cleanup twiceAtomicCapability.close() runs its cleanup once, guarded by an atomic compare-and-set
A different concurrent map on each platformJavaScript and Kotlin/Native have no shared concurrent map, so common code cannot use oneA lock-free ConcurrentHashMap that runs on every target

Limitations#

  • A slot registry is a service locator: a slot that nothing filled fails where it is read, not at start-up.
  • Adapters are registered by hand, and a forgotten registration fails when the adapter is first used. The iOS BaseController is a stub.
  • The global json configuration is a mutable variable that any code could change.
  • On JavaScript, WeakRef keeps a strong reference, so an adapter there does not let its controller go.
  • The portable ConcurrentHashMap is slower than java.util.concurrent's on the JVM.
  • Device tiers are a design. Nothing builds them yet.

Open work#

  • Fail at start-up when a required slot is missing, instead of at first use.
  • Register adapters automatically per platform, and finish the iOS BaseController.
  • Make the JSON configuration immutable, or scoped, instead of a global variable.
  • Prefer an interface with an injected implementation over expect class, which is still Beta.
  • Decide whether core's Capability should be renamed, for example to Resource, before the capability runtime adds a third meaning of the word.
  • Build the capability runtime as its own module, reaktor-capability, starting with the tier enums and the snapshot.
  • Service layer: typed services, built on core.
  • Actors: actors are nodes that close their resources and read slots at the edge.
  • FFI: the native bridge.
  • FlexBuffer: the binary format beside core's JSON defaults.