React native:注销后事件源未关闭



我想在用户注销后关闭事件源。我的代码如下。当用户注销时,推送通知仍然会出现。我的问题是如何关闭事件源?

const eventSource = new EventSource(`${environment.notificationUrl}/subscribe? 
token=${token}`);
if (!token) {
eventSource.removeAllEventListeners()
eventSource.close()
return;
}

eventSource.addEventListener('message', (event: any) => {
---- some codes here ----
}

从技术上讲,事件侦听器应该在useEffect内部订阅,并在用户注销时保持跟踪。

const NotificationSubscriptionManager = () => {
const eventSource =
new EventSource(`${environment.notificationUrl}/subscribe? 
token=${token}`);
const subScribeToNotifications = () => {
eventSource.addEventListener("message", (event: any) => {
/// ---- some codes here ----
});
};
const unsubScribeToNotifications = () => {
eventSource.removeAllEventListeners();
eventSource.close();
};
useEffect(() => {
if (!token) {
return unsubScribeToNotifications();
}
// Subscribe to notification events
subScribeToNotifications();
// Cancel all subscription when component unmount to avoid
// memory leak
return () => {
unsubScribeToNotifications();
};
}, [token]);
};

最新更新