@@ -46,7 +46,6 @@ import { JsViewFieldParser } from 'packages/core/src/parsers/viewFieldParser/JsV
4646import { Signal } from 'packages/core/src/utils/Signal' ;
4747import { parsePropPath } from 'packages/core/src/utils/prop/PropParser' ;
4848import { type BindTargetDeclaration } from 'packages/core/src/parsers/bindTargetParser/BindTargetDeclaration' ;
49- import { type MetadataSubscription } from 'packages/core/src/metadata/MetadataSubscription' ;
5049import {
5150 V_BindTargetDeclaration ,
5251 V_BindTargetScope ,
@@ -63,6 +62,10 @@ import {
6362import { validate } from 'packages/core/src/utils/ZodUtils' ;
6463import { z } from 'zod' ;
6564
65+ export interface LifecycleHook {
66+ register ( cb : ( ) => void ) : void ;
67+ }
68+
6669export interface APIFieldOverrides {
6770 inputFieldParser ?: InputFieldParser ;
6871 viewFieldParser ?: ViewFieldParser ;
@@ -680,19 +683,23 @@ export abstract class API<Plugin extends IPlugin> {
680683 * IF YOU DON'T CALL `unsubscribe` THE SUBSCRIPTION WILL LEAK MEMORY.
681684 *
682685 * @param bindTarget
686+ * @param lifecycleHook In Obsidian this is an instance of the Component class. The subscription will be automatically unsubscribed when the component is unloaded.
683687 * @param callback
684688 */
685689 public subscribeToMetadata (
686690 bindTarget : BindTargetDeclaration ,
691+ lifecycleHook : LifecycleHook ,
687692 callback : ( value : unknown ) => void ,
688- ) : MetadataSubscription {
693+ ) : void {
689694 validate (
690695 z . object ( {
691696 bindTarget : V_BindTargetDeclaration ,
697+ lifecycleHook : this . plugin . internal . getLifecycleHookValidator ( ) ,
692698 callback : z . function ( ) . args ( z . any ( ) ) . returns ( z . void ( ) ) ,
693699 } ) ,
694700 {
695701 bindTarget : bindTarget ,
702+ lifecycleHook : lifecycleHook ,
696703 callback : callback ,
697704 } ,
698705 ) ;
@@ -704,8 +711,12 @@ export abstract class API<Plugin extends IPlugin> {
704711 callback : callback ,
705712 } ) ;
706713
707- return this . plugin . metadataManager . subscribe ( uuid , signal , bindTarget , ( ) : void => {
714+ const subscription = this . plugin . metadataManager . subscribe ( uuid , signal , bindTarget , ( ) : void => {
708715 signal . unregisterAllListeners ( ) ;
709716 } ) ;
717+
718+ lifecycleHook . register ( ( ) => {
719+ subscription . unsubscribe ( ) ;
720+ } ) ;
710721 }
711722}
0 commit comments