CodeBlanks Logo Icon CodeBlanks

Summary - Native modules

Combine NativeMethods, events and TurboModules to write a native bridge.

Summary - Native modules

In this group you learned native modules, NativeMethods, platform-specific, native events and TurboModules. NativeModules carries all native modules; NativeModules.Battery.getLevel() calls a method. Platform.OS separates platforms.

NativeEventEmitter listens to native events; TurboModules provides fast calls via JSI in the new architecture. Now we will combine them into a simple native bridge skeleton.

Practice Summary - Battery level

Complete the getBattery function. Import NativeModules from react-native. Also import Platform.OS. If Platform.OS === 'android' call NativeModules.Battery.getLevel() and return it; else return null.

Starter code

App.js
import { NativeModules, Platform } from 'react-native';

export async function getBattery() {
  // on Android read the level from Battery module; else return null
}

Sample solution

App.js
import { NativeModules, Platform } from 'react-native';

export async function getBattery() {
  if (Platform.OS === 'android') {
    return await NativeModules.Battery.getLevel();
  }
  return null;
}

Practice Summary - Event cleanup

Complete the useBluetooth hook. Create an emitter with NativeEventEmitter. Listen with addListener('stateChanged', handler). Call sub.remove() in the useEffect return.

Starter code

App.js
import { useEffect } from 'react';
import { NativeEventEmitter, NativeModules } from 'react-native';

export function useBluetooth(handler) {
  useEffect(() => {
    // create emitter and listen
  }, []);
}

Sample solution

App.js
import { useEffect } from 'react';
import { NativeEventEmitter, NativeModules } from 'react-native';

export function useBluetooth(handler) {
  useEffect(() => {
    const emitter = new NativeEventEmitter(NativeModules.Bluetooth);
    const sub = emitter.addListener('stateChanged', handler);
    return () => sub.remove();
  }, []);
}

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Match the flow parts

Term Meaning
NativeModules All modules
Platform.OS Operating system
NativeEventEmitter Listens to events
TurboModules New architecture

2 The EventEmitter class

Question
const emitter = new ____(NativeModules.Bluetooth);
Answer
const emitter = new NativeEventEmitter(NativeModules.Bluetooth);

Explanation: NativeEventEmitter listens to native events.

All lessons in Advanced