The shell
Type generation gives each shell three things to build on:
- the app's types (
Event,Effect,ViewModeland the rest), - an
EffectHandlerinterface, with one method per operation the app can ask for, and - a
Coreclass that runs the loop: it sends events to the Rust core, hands each effect to yourEffectHandler, resolves the request with what your method returns, and publishes the new view model whenever the core asks for a render.
So a shell writes its UI and an EffectHandler. The counter's only effect is
Render, which Core handles itself, so its handler is empty.
Who drives the loop in Part II
explains how this fits together, and
The generated Core has the exact
shape in each language.
Setting up the project
The quickest way to start is to copy the shell you want from
examples/counter.
Each one has a Justfile: just dev runs the codegen, packages the core with
BoltFFI, and builds the shell. If you'd rather set the project up from
scratch, Part I's shell chapters walk through it for
iOS/macOS,
Android and
React. Their project setup applies here too,
with two differences, because here the generated package depends on the
BoltFFI one:
- In
apple/project.yml, the app target needs only the generatedApppackage. It reaches the BoltFFISharedpackage throughApp. - On the web, run
boltffi pack wasmbefore the TypeScript codegen, because the generated package installs the wasm one as a dependency.
The code that differs is what follows.
iOS/macOS
The handler conforms to the generated EffectHandler protocol:
// Swift: apple/CounterApp/CounterHandler.swift
import App
/// `CounterHandler` is the shell's side of the effect protocol: it implements
/// the generated `EffectHandler`, which has one method per operation the app
/// declares.
///
/// The counter's only effect is `Render`, and the generated `Core` intercepts
/// that before the dispatcher sees it, so the protocol's default no-op stands
/// and there is nothing here to write.
struct CounterHandler: EffectHandler {}
The app builds a Core from it, keeps it in @State, and puts it in the
environment:
// Swift: apple/CounterApp/CounterApp.swift
import App
import SwiftUI
@main
struct CounterApp: App {
@State private var core = Core(handler: CounterHandler())
var body: some Scene {
WindowGroup {
ContentView()
.environment(core)
}
}
}
Core is @Observable, so a view that reads core.view redraws when the view
model changes. The buttons send events with core.update:
// Swift: apple/CounterApp/ContentView.swift
struct ContentView: View {
@Environment(Core.self) var core
var body: some View {
VStack {
Image(systemName: "globe")
.imageScale(.large)
.foregroundColor(.accentColor)
Text(core.view.count)
HStack {
ActionButton(label: "Reset", color: .red) {
core.update(.reset)
}
ActionButton(label: "Inc", color: .green) {
core.update(.increment)
}
ActionButton(label: "Dec", color: .yellow) {
core.update(.decrement)
}
}
}
}
}
Android
The handler implements the generated EffectHandler interface:
// Kotlin: Android/app/src/main/java/com/crux/examples/counter/CounterHandler.kt
package com.crux.examples.counter
/**
* The shell's side of the effect protocol: the generated `EffectHandler` has
* one method per operation the app declares.
*
* The counter's only effect is `Render`, and the generated `Core` intercepts
* that before the dispatcher sees it and refreshes its `view` flow, so the
* interface's default no-op stands and there is nothing here to write.
*/
object CounterHandler : EffectHandler
Core needs a CoroutineScope on the main dispatcher, and an Android
ViewModel provides one that lives as long as the screen does:
// Kotlin: Android/app/src/main/java/com/crux/examples/counter/CounterViewModel.kt
package com.crux.examples.counter
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
/**
* An Android `ViewModel` (not the app's `ViewModel`, which `Core.view`
* publishes) that holds the generated `Core`, so the count survives a
* configuration change.
*
* `viewModelScope` runs on `Dispatchers.Main.immediate` with a
* `SupervisorJob`, which is what `Core` needs, and is cancelled when
* Android clears this `CounterViewModel`.
*/
class CounterViewModel : ViewModel() {
val core = Core(CounterHandler, viewModelScope)
}
Core publishes the app's ViewModel (the Crux one) as a StateFlow, which
Compose collects:
// Kotlin: Android/app/src/main/java/com/crux/examples/counter/MainActivity.kt
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
CounterTheme {
Surface(
modifier = Modifier.fillMaxSize(),
color = MaterialTheme.colorScheme.background
) {
// The generated `Core` over the generated `FfiBridge`:
// the shell writes the handler and never sees the FFI.
val core = viewModel<CounterViewModel>().core
val view by core.view.collectAsState()
View(view, core::update)
}
}
}
}
}
Web (TypeScript)
The handler implements the generated EffectHandler interface, and
Core.create builds the core from it, with a callback for each new view
model. It's an async factory, because the wasm module loads asynchronously:
// TypeScript: web-nextjs/src/app/core.ts
import type { EffectHandler, ViewModel } from "shared_types/app";
import { Core } from "shared_types/app";
/**
* The shell's side of the effect protocol.
*
* `CounterHandler` implements the generated `EffectHandler`, which has one
* method per operation the app declares. The counter's only effect is
* `Render`, and the generated `Core` handles that itself (reading the new
* view model and passing it to the `onView` callback), so there is nothing
* left for the handler to do.
*/
export class CounterHandler implements EffectHandler {}
/**
* Everything the shell has to write to run a Crux core: an `EffectHandler`
* for the app's operations and a callback for the view model. `Core.create`
* waits for the wasm module, builds the generated `FfiBridge` over it, and
* owns the loop between them.
*/
export function createCore(onView: (view: ViewModel) => void): Promise<Core> {
return Core.create(new CounterHandler(), onView);
}
The page creates the core once, passing React's setView as the callback:
// TypeScript: web-nextjs/src/app/page.tsx
const Home: NextPage = () => {
const [view, setView] = useState(new ViewModel(""));
const core = useRef<Core | null>(null);
const initialized = useRef(false);
useEffect(() => {
if (initialized.current) return;
initialized.current = true;
void createCore(setView).then((created) => {
core.current = created;
// `onView` is only called on a render, so show the initial view now.
setView(created.view);
});
}, []);
Windows (C#)
The handler implements the generated IEffectHandler interface:
// C#: windows/CounterApp/CounterHandler.cs
using CounterApp.Shared;
namespace CounterApp;
/// <summary>
/// The shell's side of the effect protocol: the generated
/// <c>IEffectHandler</c> has one method per operation the app declares.
///
/// The counter's only effect is <c>Render</c>, and the generated <c>Core</c>
/// intercepts that before the dispatcher sees it and raises
/// <c>PropertyChanged</c> for its <c>View</c>, so the interface's default
/// no-op stands and there is nothing here to write.
/// </summary>
public sealed class CounterHandler : IEffectHandler
{
}
The app builds the Core from it when it launches:
// C#: windows/CounterApp/App.xaml.cs
protected override void OnLaunched(LaunchActivatedEventArgs args)
{
var viewModel = new CounterViewModel(new Core(new CounterHandler()));
window = new MainWindow(viewModel);
window.Activate();
}
Core raises PropertyChanged for its View, which the
CounterViewModel
mirrors into a property the window binds to.
Rust shells
A shell written in Rust, like
Leptos, uses the core directly and matches on
the Effect enum itself. There's no generated Core to use there, and no need
for one: in Rust, the match is already as precise as a handler interface.
Run just dev in the shell's directory, then open the project in Xcode or
Android Studio (or Visual Studio on Windows), or run just serve for the web, and you have a working
counter. Next, let's give it a capability.