Example Svelte Integration
Relevant source files
The following files were used as context for generating this wiki page:
The Example Svelte Integration serves as a comprehensive demonstration of using the tauri-plugin-centrifugo-api within a modern web framework context. This implementation showcases real-time communication patterns between a Tauri frontend and a Centrifugo server, highlighting connection management, message publishing, and event-driven data handling.
The integration is built using Svelte, Vite, and TypeScript, providing a reactive user interface to interact with the Centrifugo plugin's backend commands and frontend event listeners. It serves as both a reference implementation for developers and a functional testing environment for the plugin's capabilities.
Sources: examples/tauri-app/README.md, examples/tauri-app/package.json, README.md:252-259
Core Architecture and Lifecycle
The Svelte integration follows a standard Tauri application structure where the frontend communicates with a Rust backend via the Centrifugo plugin. The application lifecycle begins with the initialization of the plugin API and the setup of asynchronous event listeners to capture server state changes.
Lifecycle Flow
- Mounting: Upon the
onMountlifecycle hook, the application waits for the Tauri API to initialize. - Listener Registration: Asynchronous functions such as
onConnectedandonPublicationare registered. - State Management: Configuration is loaded from
localStorageto restore previous sessions. - Cleanup: Unlisten functions are stored in an array and executed when the component is destroyed to prevent memory leaks.
Sources: examples/tauri-app/src/App.svelte:49-65, examples/tauri-app/src/main.ts:1-10
The diagram above illustrates the initialization and cleanup lifecycle of the Svelte integration.
Sources: examples/tauri-app/src/App.svelte:49-65
Connection Management
Connection management is handled through a reactive form that binds to the StartConfig interface parameters. The application supports establishing WebSocket connections with optional JWT authentication and protocol selection (JSON vs Protobuf).
Connection Parameters
| Parameter | Description | UI Binding |
|---|---|---|
url | WebSocket URL for Centrifugo | input#url |
token | Optional JWT authentication token | input#token |
name | Client identifier | input#clientName |
channels | Initial comma-separated list of channels | input#channels |
useProtobuf | Toggle for protocol format | input[type="checkbox"] |
readTimeout | Connection timeout in milliseconds | input#readTimeout |
Sources: examples/tauri-app/src/App.svelte:26-32, README.md:200-208
Connection Flow
The connection process is initiated via the connectToCentrifugo function, which parses the user input and calls the plugin's connect command.
Event Handling and Logging
The integration implements an extensive event-driven system to provide real-time feedback to the user. Every state transition in the Centrifugo connection (connecting, connected, disconnected, error) and every data event (publication, subscription changes) is captured and logged to a dual-log UI system.
Event Listeners
| Listener | Trigger | Action |
|---|---|---|
onConnecting | Socket starts handshake | Sets status to 'Connecting...' |
onConnected | Handshake successful | Sets status to 'Connected' |
onPublication | Message received on channel | Decodes data and logs result |
onError | WebSocket or protocol error | Logs error to the error console |
onSubscribed | Successfully joined a channel | Updates local subscriptions record |
Sources: examples/tauri-app/src/App.svelte:70-138, README.md:95-127
Data Decoding
When a message is received via onPublication, the payload typically contains base64 encoded data. The Svelte integration uses utils.decodeJson to transform this data into a readable object before displaying it in the event log.
// Data processing snippet
if (data.data) {
try {
const decodedData = utils.decodeJson(data.data)
addToLog(`📄 Decoded data: ${JSON.stringify(decodedData, null, 2)}`)
} catch (decodeError) {
addToLog(`📄 Raw data (base64): ${data.data}`)
}
}
Sources: examples/tauri-app/src/App.svelte:121-131
Channel and RPC Operations
The integration demonstrates advanced interactions beyond simple message reception, including dynamic subscription management and Remote Procedure Calls (RPC).
Subscription Logic
Subscriptions can be added or removed dynamically without reconnecting the primary socket. The addSubscription function allows users to join new channels, while removeSubscription exits them. The UI reactively updates a list of active channels, providing individual "Test" and "Unsubscribe" buttons for each.
RPC Implementation
The application allows executing RPC methods by specifying a method name and a JSON payload. It utilizes helpers.rpcJson to handle the serialization and deserialization of the request and response data.
Summary
The Example Svelte Integration provides a robust blueprint for implementing real-time features in Tauri applications. By leveraging the tauri-plugin-centrifugo-api, it manages complex WebSocket lifecycles and data transformations while maintaining a clean, reactive frontend state. It effectively demonstrates the plugin's utility in handling both standard pub/sub patterns and advanced RPC interactions.
Sources: examples/tauri-app/src/App.svelte, README.md:252-259