You're between sets, your phone is in your bag across the gym, and you tap "log set" on your watch. What should happen?
That's the problem I had to solve when I added a Wear OS app to Gainr, the strength training app I build with Expo and React Native. The watch app logs sets for a workout running on the phone and shows live heart rate and calories. It's plain Kotlin and Compose for Wear OS, since React Native doesn't run on the watch. This post covers how that native app sits inside an Expo project and how the watch stays usable when it can't reach the phone.
I don't own a Wear OS watch yet, so everything here was tested on the Wear OS emulator paired with a phone emulator.
Keep the watch app out of android/
With Continuous Native Generation, android/ is generated, and prebuild --clean throws it away. So the watch app lives in its own folder, targets/wear/, as a normal Gradle module.
A config plugin adds that module to the generated project and passes a few values from the app config to it as Gradle properties. This is a complete, minimal version:
// plugins/withWearApp.js
const { withSettingsGradle, withGradleProperties } = require("@expo/config-plugins");
const MARKER = "// wear app module";
module.exports = function withWearApp(config, { versionCode } = {}) {
config = withSettingsGradle(config, (config) => {
if (!config.modResults.contents.includes(MARKER)) {
config.modResults.contents += `
${MARKER}
include ':wear'
project(':wear').projectDir = new File(rootDir, '../targets/wear')
`;
}
return config;
});
return withGradleProperties(config, (config) => {
const values = {
"myapp.wearPackage": config.android?.package,
"myapp.wearVersionName": config.version,
"myapp.wearVersionCode": versionCode && String(versionCode),
};
for (const [key, value] of Object.entries(values)) {
// Drop the old value so repeated prebuilds don't stack duplicates.
config.modResults = config.modResults.filter(
(item) => !(item.type === "property" && item.key === key),
);
if (value) config.modResults.push({ type: "property", key, value });
}
return config;
});
};
Register it in app.config.js:
plugins: [
["./plugins/withWearApp", { versionCode: 2000001 }],
],
And read the properties in targets/wear/build.gradle, with fallbacks so the module still builds on its own:
def prop = { String name, String fallback ->
rootProject.findProperty(name)?.toString() ?: fallback
}
android {
defaultConfig {
applicationId prop("myapp.wearPackage", "com.example.myapp")
versionCode Integer.parseInt(prop("myapp.wearVersionCode", "1"))
versionName prop("myapp.wearVersionName", "1.0.0")
minSdkVersion 30
}
}
The watch module's main dependencies:
implementation "androidx.wear.compose:compose-material3:1.7.1"
implementation "androidx.wear.compose:compose-foundation:1.7.1"
implementation "androidx.wear:wear-ongoing:1.1.0"
implementation "androidx.health:health-services-client:1.1.0"
implementation "com.google.android.gms:play-services-wearable:19.0.0"
Three things about this setup:
-
The package name and signing certificate must match the phone app. The Wearable Data Layer only connects a watch app and a phone app that share both. That's why the plugin hands the phone's
android.packageto the watch build instead of giving the watch its own ID. Sign both release builds with the same upload key. -
The version name follows the app, the version code doesn't. Both builds go to the same Play listing, so the watch needs its own
versionCode, different from the phone's. If you let EAS manage the phone's version code remotely, the plugin can't see it, so set the watch's code yourself. -
EAS builds only the phone app. After
npx expo prebuild, run./gradlew :wear:installDebugfromandroid/with a watch emulator or device selected (adb -s <serial>orANDROID_SERIAL). For release,./gradlew :wear:bundleReleasegives you a separate bundle to upload.
The phone owns the workout
The phone saves the workout. The watch sends commands and shows what it's waiting on. Everything else follows from that.
The Data Layer has two pieces that fit this split:
-
State is one data item, say
/workout/state, holding the active workout with its exercises and sets. The Data Layer keeps a synced copy on the watch, so when the watch app opens it reads the last state it has without asking the phone. -
Each watch action is its own data item, say
/workout/command/<id>. OnceputDataItemsucceeds on the watch, the Data Layer holds the item and syncs it when the phone is reachable again.
That second point has a catch: the Data Layer only carries items that were stored successfully. If the put fails, nothing is queued for you, so keep the command on the watch until the phone confirms it:
fun send(command: Command) {
pendingCommands.update { it + command } // stays here until the phone acks it
val request = PutDataMapRequest.create("/workout/command/${command.id}").apply {
dataMap.putString("json", command.toJson())
dataMap.putLong("createdAt", command.createdAt)
}.asPutDataRequest().setUrgent()
scope.launch { runCatching { dataClient.putDataItem(request).await() } }
}
Show pending changes on the watch
If you log a set while the phone is unreachable, the watch can't wait for the next phone state to show it. So the watch draws the phone's last state with its pending commands applied on top:
val displayed: StateFlow<Workout?> =
combine(phoneState, pendingCommands) { state, pending ->
state?.workout?.let { workout -> pending.fold(workout) { w, cmd -> cmd.applyTo(w) } }
}.stateIn(scope, SharingStarted.Eagerly, null)
Each state the phone publishes includes the IDs of the commands it has handled. The watch drops those from its pending list, plus any commands that belong to a different workout. A handled command isn't always a successful one: if saving fails, the phone still acknowledges the command and sends an error the watch can show. Without that, a failed command would sit in the pending list forever and the watch would keep showing a set the phone never saved.
The phone side: buffer, dedupe, hand off
On the phone, a local Expo module receives command items and passes them to JavaScript. Two things make this harder than a listener:
-
Items can arrive while the app is closed. When the module starts, it queries for any command items already waiting (a
wear://*/workout/commandprefix query withDataClient.getDataItems). - The same item can show up twice, once from that startup query and again from a change event. The module keys its buffer by data item URI, so each item is buffered once.
JavaScript pulls the buffer sorted by createdAt. The module then deletes the items from the Data Layer, so it stops being responsible for them before the set is saved. JavaScript runs one command at a time, skips any command ID it has already handled, and acknowledges each one when it finishes, whether the save worked or not. If the phone app dies between taking a command and saving it, that command is gone. The watch still has it in its pending list, which is where you'd add a resend if you need one.
Watch commands and taps on the phone end up calling the same backend mutation, so "log a set" is saved by the same server code either way. The client handlers are separate.
Opening the watch app from the phone
When a workout starts on the phone, the phone can open the watch app. The watch app declares a capability in res/values/wear.xml. The phone asks for reachable nodes with that capability and starts the watch activity with RemoteActivityHelper:
val nodes = Wearable.getCapabilityClient(context)
.getCapability("myapp_wear", CapabilityClient.FILTER_REACHABLE)
.await()
.nodes
val intent = Intent(Intent.ACTION_VIEW)
.addCategory(Intent.CATEGORY_BROWSABLE)
.setData(Uri.parse("myapp-wear://workout"))
nodes.forEach { RemoteActivityHelper(context).startRemoteActivity(intent, it.id).await() }
"Reachable" means the Data Layer can reach the node right now. It doesn't tell you anything about Bluetooth distance. If no node with the app is reachable, nothing opens.
Heart rate and calories with Health Services
While a workout is in progress, the watch runs a Health Services exercise, the Wear OS counterpart of an Apple Watch HealthKit workout session. It gives you live heart rate and active calories. Its foreground service shows an ongoing activity, so the app stays one tap from the watch face.
- It needs sensor permissions, and the device has to support the metrics. Check capabilities before you show a heart rate tile.
- Only one app can run an exercise at a time. Starting yours ends one another app is running.
- Final numbers can arrive after the phone has saved the workout. So the watch sends average heart rate and calories as one more command tagged with the workout's ID, and the phone attaches them to the saved workout.
A test worth running
The setup is only as good as the offline case, so test that directly:
- Start a workout on the phone, open the watch app.
- Make the phone unreachable (on emulators, turn off the phone emulator's network or stop it).
- Log two sets on the watch. Both should show right away as pending.
- Bring the phone back. Check that the phone saves exactly two sets, not three, and that the watch clears both from its pending list.
- Repeat, but end the workout on the phone while the watch is offline. When they reconnect, the watch should clear those sets rather than keep them pending forever.
Step 4 catches duplicate delivery. Step 5 catches commands that never get acknowledged or cleared.
Gainr is on Google Play, with the Wear OS app in the same listing. If you're building a companion watch app with Expo, I'd like to hear how you handled the offline case.
Top comments (0)