@amityco/ts-sdk-react-native
Version:
Amity Social Cloud Typescript SDK
47 lines (38 loc) • 1.37 kB
text/typescript
import { getActiveClient } from '~/client/api/activeClient';
import { createEventSubscriber } from '~/core/events';
import { pullFromCache, upsertInCache } from '~/cache/api';
type CallbackFn = Amity.Listener<Amity.StaticInternalChannel>;
const callbacks: CallbackFn[] = [];
let mainDisposer: (() => void) | null = null;
const dispose = (cb: CallbackFn) => {
const index = callbacks.indexOf(cb);
if (index > -1) {
callbacks.splice(index, 1);
}
if (callbacks.length === 0) {
mainDisposer?.();
}
};
export const onChannelSetMuted = (callback: Amity.Listener<Amity.StaticInternalChannel>) => {
if (callbacks.length === 0) {
const client = getActiveClient();
const filter = async (payload: Amity.ChannelSetMutedPayload) => {
upsertInCache(['channel', 'get', payload.channelId], {
// If muteTimeout > now => user is muted
// Otherwise => user is unmuted
isMuted: Date.parse(payload.muteTimeout) > Date.now(),
});
const channel = pullFromCache<Amity.StaticInternalChannel>([
'channel',
'get',
payload.channelId,
])?.data;
if (channel) {
callbacks.forEach(cb => cb(channel));
}
};
mainDisposer = createEventSubscriber(client, 'onChannelMute', 'channel.setMuted', filter);
}
callbacks.push(callback);
return () => dispose(callback);
};