@@ -19,18 +19,21 @@ class FiberStoreImpl<R, E, A> implements FiberStore.FiberStore<R, E, A> {
1919 readonly runtime : Runtime . Runtime < R >
2020 ) { }
2121
22+ // listeners
2223 private listeners : Array < ( ) => void > = [ ]
23-
24+ private notify ( ) {
25+ for ( let i = 0 ; i < this . listeners . length ; i ++ ) {
26+ this . listeners [ i ] ( )
27+ }
28+ }
2429 public subscribe = ( listener : ( ) => void ) => {
2530 this . listeners . push ( listener )
26-
27- if ( ! this . fiberState && this . stream ) {
28- this . run ( this . stream )
29- }
30-
31+ this . maybeResume ( )
3132 return ( ) => {
32- this . listeners . splice ( this . listeners . indexOf ( listener ) , 1 )
33-
33+ const index = this . listeners . indexOf ( listener )
34+ if ( index >= 0 ) {
35+ this . listeners . splice ( index , 1 )
36+ }
3437 queueMicrotask ( ( ) => {
3538 if ( this . listeners . length === 0 ) {
3639 this . interruptIfRunning ( )
@@ -39,30 +42,29 @@ class FiberStoreImpl<R, E, A> implements FiberStore.FiberStore<R, E, A> {
3942 }
4043 }
4144
45+ // state
4246 private trackedProps = TrackedProperties . initial ( )
4347 private resultBag : ResultBag . ResultBag < E , A > = ResultBag . make ( Result . initial ( ) , this . trackedProps )
4448 private setResult ( result : Result . Result < E , A > ) {
4549 TrackedProperties . updateFromResult ( this . trackedProps , result )
4650 this . resultBag = ResultBag . make ( result , this . trackedProps )
47- for ( let i = 0 ; i < this . listeners . length ; i ++ ) {
48- this . listeners [ i ] ( )
49- }
51+ this . notify ( )
5052 }
5153 public snapshot = ( ) => {
5254 return this . resultBag
5355 }
5456
57+ // lifecycle
5558 private stream : Stream . Stream < R , E , A > | undefined = undefined
5659 private fiberState :
5760 | {
5861 readonly fiber : Fiber . RuntimeFiber < never , void >
5962 readonly interruptedRef : Ref . Ref < boolean >
6063 }
6164 | undefined = undefined
62-
6365 public run ( stream : Stream . Stream < R , E , A > ) {
64- this . stream = stream
6566 this . interruptIfRunning ( )
67+ this . stream = stream
6668
6769 const interruptedRef = Ref . unsafeMake ( false )
6870 const maybeSetResult = ( result : Result . Result < E , A > ) =>
@@ -89,7 +91,6 @@ class FiberStoreImpl<R, E, A> implements FiberStore.FiberStore<R, E, A> {
8991 interruptedRef
9092 }
9193 }
92-
9394 public interruptIfRunning ( ) {
9495 if ( this . fiberState ) {
9596 Effect . runFork (
@@ -101,4 +102,9 @@ class FiberStoreImpl<R, E, A> implements FiberStore.FiberStore<R, E, A> {
101102 this . fiberState = undefined
102103 }
103104 }
105+ private maybeResume ( ) {
106+ if ( ! this . fiberState && this . stream ) {
107+ this . run ( this . stream )
108+ }
109+ }
104110}
0 commit comments