WhoBuilt

Adding Event Emitters to Your TurboModule in Swift

Dec 30, 2025· 11 min· 428 views·Watch on YouTube

Speaker

Oscar from Callstack explains how to add event emitters to a Swift TurboModule in a React Native tutorial.

What event emitters do

Event emitters let native code notify JavaScript when something changes. Oscar uses a local storage module as an example: when a new key is added, it can send the key and value to JavaScript so the app can respond.

Define the event and connect the native layers

Oscar adds an `onKeyAdded` event with a string key and string value to the module spec, then reruns Codegen. The generated iOS base class provides an `emitOnKeyAdded` method. In Swift, the module stores the callback as an escaping closure so it can call it later.

Emit only when a key is new

In `setItem`, the Swift code checks whether the key already exists in UserDefaults. It invokes the callback for a new key, while updates to existing keys do not notify JavaScript. Objective-C packages the values in a dictionary and calls the generated emitter method.

Break the retain cycle

Although the app compiles, Oscar points out that the Objective-C and Swift objects can keep each other alive through strong references. He uses a weak reference to `LocalStorage` in the closure before calling `emitOnKeyAdded`, which avoids that retain cycle.

Subscribe and verify the event

The JavaScript example subscribes in `useEffect` and removes the subscription when the component unmounts. Testing shows that adding a new key triggers an alert with its key and value, while setting an existing key does not. Oscar traces the call from JavaScript through Objective-C and Swift, then back to JavaScript.

Takeaways

  • Use Codegen's event emitter type in the module spec, then regenerate the native interfaces.
  • Store the Swift callback as an escaping closure when it must be invoked after initialization.
  • Check whether a key is new before emitting, so updates do not produce new-key events.
  • Capture the Objective-C module weakly in the callback to avoid a retain cycle.
  • Subscribe in `useEffect` and clean up the listener when the component unmounts.

Mentioned in this talk

Search inside this talk

What was claimed 4

  • feature
    TurboModules: Can emit native events to JavaScript
    “lets us inform JavaScript about a change that happened in native”
    YouTube
    Unverified1 source· Talk
  • feature
    code generation: Generates an emitOnKeyAdded method for the native event emitter
    “a new emitOnKeyAdded method we can use”
    YouTube
    Unverified1 source· Talk
  • feature
    Arc: Manages memory using reference counts
    “Each object has a reference counter”
    YouTube
    Unverified1 source· Talk
  • feature
    Callstack: Publishes the Mastering React Native Turbo Modules video series
    “subscribe to the Callstack channel”
    YouTube
    Unverified1 source· Talk

Related talks