@@ -46,7 +46,6 @@ import { JsViewFieldParser } from 'packages/core/src/parsers/viewFieldParser/JsV
46
46
import { Signal } from 'packages/core/src/utils/Signal' ;
47
47
import { parsePropPath } from 'packages/core/src/utils/prop/PropParser' ;
48
48
import { type BindTargetDeclaration } from 'packages/core/src/parsers/bindTargetParser/BindTargetDeclaration' ;
49
- import { type MetadataSubscription } from 'packages/core/src/metadata/MetadataSubscription' ;
50
49
import {
51
50
V_BindTargetDeclaration ,
52
51
V_BindTargetScope ,
@@ -63,6 +62,10 @@ import {
63
62
import { validate } from 'packages/core/src/utils/ZodUtils' ;
64
63
import { z } from 'zod' ;
65
64
65
+ export interface LifecycleHook {
66
+ register ( cb : ( ) => void ) : void ;
67
+ }
68
+
66
69
export interface APIFieldOverrides {
67
70
inputFieldParser ?: InputFieldParser ;
68
71
viewFieldParser ?: ViewFieldParser ;
@@ -680,19 +683,23 @@ export abstract class API<Plugin extends IPlugin> {
680
683
* IF YOU DON'T CALL `unsubscribe` THE SUBSCRIPTION WILL LEAK MEMORY.
681
684
*
682
685
* @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.
683
687
* @param callback
684
688
*/
685
689
public subscribeToMetadata (
686
690
bindTarget : BindTargetDeclaration ,
691
+ lifecycleHook : LifecycleHook ,
687
692
callback : ( value : unknown ) => void ,
688
- ) : MetadataSubscription {
693
+ ) : void {
689
694
validate (
690
695
z . object ( {
691
696
bindTarget : V_BindTargetDeclaration ,
697
+ lifecycleHook : this . plugin . internal . getLifecycleHookValidator ( ) ,
692
698
callback : z . function ( ) . args ( z . any ( ) ) . returns ( z . void ( ) ) ,
693
699
} ) ,
694
700
{
695
701
bindTarget : bindTarget ,
702
+ lifecycleHook : lifecycleHook ,
696
703
callback : callback ,
697
704
} ,
698
705
) ;
@@ -704,8 +711,12 @@ export abstract class API<Plugin extends IPlugin> {
704
711
callback : callback ,
705
712
} ) ;
706
713
707
- return this . plugin . metadataManager . subscribe ( uuid , signal , bindTarget , ( ) : void => {
714
+ const subscription = this . plugin . metadataManager . subscribe ( uuid , signal , bindTarget , ( ) : void => {
708
715
signal . unregisterAllListeners ( ) ;
709
716
} ) ;
717
+
718
+ lifecycleHook . register ( ( ) => {
719
+ subscription . unsubscribe ( ) ;
720
+ } ) ;
710
721
}
711
722
}
0 commit comments