A Tauri plugin that provides a thin abstraction layer over Tauri event system.
Channel is a Tauri plugin that provides an ergonomic layer for creating “scoped channels” between frontend and backend.
- Simplifies Tauri event system hiding details like event-name
- Channels don't interfere with each other: events are self-contained
- Automatically closes frontend listener when each backend sender has been dropped
Imagine a download manager application that shows different progress bar for each file being downloaded from the backend.
A classic Tauri app :
- Should know and manage different event name, one for each download
- Alternatively, provides a custom partition mechanism in the event payload to distinguish events receiver
Using Channel, each fn download (link: String)
from backend will return its channel where download progress events will be published from backend and are visible only to frontend component that owns that channel.
Install the Core plugin by adding the following to your Cargo.toml file:
src-tauri/Cargo.toml
[dependencies]
tauri-plugin-channel = { git = "https://github.com/fourviere/tauri-plugin-channel" }
You can install the JavaScript Guest bindings using your preferred JavaScript package manager:
npm add https://github.com/fourviere/tauri-plugin-channel
- Register the channel plugin with Tauri:
src-tauri/src/main.rs
fn main() {
tauri::Builder::default()
.plugin(tauri_plugin_channel::init())
.run(tauri::generate_context!())
.expect("error while running tauri application");
}
- Return the channel in the tauri::command
src-tauri/src/main.rs
use tauri_plugin_channel;
#[derive(Clone, Serialize)]
enum BackendEvents {
Progress(u8),
}
#[tauri::command]
fn example_function (app_handle: AppHandle) -> Channel {
let (sender, receiver, channel) = channel(app_handle);
tokio::spawn({
for i in 0..100
tokio::sleep(Duration::from_secs(i)).await
sender.emit(BackendEvents::Progress(i)).await;
});
tokio::spawn({
println!(receiver.once::<String>().await)
});
channel
}
Use the Receiver.receive, Sender.emit
functions to receive or send events to/from backend
import {channel} from "tauri-plugin-channel-api"
import type {Sender, Receiver} from "tauri-plugin-channel-api"
type BackendEvents = { Progress: number }
[sender, receiver] = await channel('example_function')
receiver.listen<BackendEvents>(event => console.log(JSON.stringify(event)));
sender.emit(channel, "1");
- Install dependencies.
npm install
- Build the app
npm run dev