From b9a1df93b5ee2b793f67c3a95210467289abdb8e Mon Sep 17 00:00:00 2001 From: qschroter Date: Tue, 5 Nov 2024 17:00:45 +0100 Subject: [PATCH] add subscribe composable factory --- src/Bones.UI/abstractions/inotifyService.ts | 4 +++- src/Bones.UI/core/composableFactory.ts | 21 +++++++++++++++++++ .../services/testUserService.ts | 7 +++++++ 3 files changed, 31 insertions(+), 1 deletion(-) diff --git a/src/Bones.UI/abstractions/inotifyService.ts b/src/Bones.UI/abstractions/inotifyService.ts index 5cacd7b..75a40f5 100644 --- a/src/Bones.UI/abstractions/inotifyService.ts +++ b/src/Bones.UI/abstractions/inotifyService.ts @@ -15,4 +15,6 @@ export type AllEvent = NotifyEvent | "all"; export type AddOrUpdateCallback = (ev: AddOrUpdateEvent, payload: TDetails) => void; export type DeleteCallback = (ev: DeleteEvent, id: any) => void; export type ResetCallback = (ev: ResetEvent) => void; -export type AllCallback = AddOrUpdateCallback | DeleteCallback | ResetCallback; \ No newline at end of file +export type AllCallback = AddOrUpdateCallback | DeleteCallback | ResetCallback; + +export type SubscribeCall = [AddOrUpdateEvent, AddOrUpdateCallback] | [DeleteEvent, DeleteCallback] | [ResetEvent, ResetCallback] | [AllEvent, AllCallback]; \ No newline at end of file diff --git a/src/Bones.UI/core/composableFactory.ts b/src/Bones.UI/core/composableFactory.ts index e9419c7..b2d9aa8 100644 --- a/src/Bones.UI/core/composableFactory.ts +++ b/src/Bones.UI/core/composableFactory.ts @@ -25,6 +25,27 @@ export class ComposableFactory { return ComposableFactory.customRemove(service.remove); } + public static subscribe(service: INotifyService) { + return () => { + let subscribersIds: number[] = []; + + onUnmounted(() => { + subscribersIds.forEach(id => service.unsubscribe(id)); + subscribersIds = []; + }); + + const subscribe: INotifyService["subscribe"] = (ev: any, callback: any) => { + const subscriberId = service.subscribe(ev, callback); + subscribersIds.push(subscriberId); + return subscriberId; + } + + return { + subscribe + } + } + } + public static custom(method: (...args: TArgs) => Promise, applyFactory?: () => (entity: Ref) => void) { return () => { const apply = applyFactory ? applyFactory() : () => { }; diff --git a/tests/Bones.UI.Tests/services/testUserService.ts b/tests/Bones.UI.Tests/services/testUserService.ts index 5b4c9e3..2bb3b96 100644 --- a/tests/Bones.UI.Tests/services/testUserService.ts +++ b/tests/Bones.UI.Tests/services/testUserService.ts @@ -23,6 +23,13 @@ const AccountLoginFactory = new ServiceFactory(testUserServiceFactory); export const useTestUserTrack = ComposableFactory.trackRef(testUserServiceFactory); +export const useTestUserSubscribe = ComposableFactory.subscribe(testUserServiceFactory); + +const { subscribe } = useTestUserSubscribe(); + +subscribe("add", (ev, payload) => { + console.log(ev, payload); +}); export const useLogin = ComposableFactory.custom(AccountLoginFactory.login, () => { const { sync } = useTestUsersSync();