Change IPC Channel onmessage Handler Dynamically During Use #14765
-
|
Hi, I was wondering if the setting the I would like to do this as I have to bind a new handler if the user navigate away from the page and then come back, I would like to ensure the front end still receive updates after the user is back (the channel is globally persisted, so it is always the same |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments
-
|
Reassigning That said, for the "user leaves and comes back" case I'd keep import { Channel } from '@tauri-apps/api/core'
class StableChannel<T> {
channel = new Channel<T>()
listeners = new Set<(d: T) => void>()
constructor() {
this.channel.onmessage = (d) => this.listeners.forEach(l => l(d))
}
subscribe(l: (d: T) => void) {
this.listeners.add(l)
return () => this.listeners.delete(l)
}
}
export const updates = new StableChannel<MyUpdate>()Pass |
Beta Was this translation helpful? Give feedback.
-
|
To add a concrete implementation for the "user navigates away and comes back" use case: Reassigning Robust pattern: stable channel + subscriber registryKeep the TypeScript (framework-agnostic) import { Channel } from '@tauri-apps/api/core';
class StableChannel<T> {
readonly channel = new Channel<T>();
private listeners = new Set<(data: T) => void>();
constructor() {
this.channel.onmessage = (data) => {
this.listeners.forEach(l => l(data));
};
}
subscribe(listener: (data: T) => void): () => void {
this.listeners.add(listener);
return () => this.listeners.delete(listener); // returns unsubscribe fn
}
}
// Singleton, created once and passed to Rust on first use
export const streamChannel = new StableChannel<MyUpdate>();In your component (React example) useEffect(() => {
const unsubscribe = streamChannel.subscribe((data) => {
setState(data);
});
return unsubscribe; // clean unsubscribe on unmount
}, []);In your component (Angular example) ngOnInit() {
this.unsub = streamChannel.subscribe(data => this.data = data);
}
ngOnDestroy() {
this.unsub?.();
}This way:
|
Beta Was this translation helpful? Give feedback.
Reassigning
onmessageis safe —Channelcalls whatever's currently ononmessageat message time, no captured reference from creation. Swapping mid-stream works.That said, for the "user leaves and comes back" case I'd keep
onmessagestable and dispatch via a registry, because reassigning from a component is fragile (you can drop the new handler if a remount races the reassignment):