7
7
module Reflex.Host.Headless where
8
8
9
9
import Control.Concurrent.Chan (newChan , readChan )
10
+ import Control.Monad (unless )
10
11
import Control.Monad.Fix (MonadFix , fix )
11
12
import Control.Monad.IO.Class (MonadIO , liftIO )
12
13
import Control.Monad.Primitive (PrimMonad )
@@ -15,7 +16,7 @@ import Data.Dependent.Sum (DSum (..), (==>))
15
16
import Data.Foldable (for_ )
16
17
import Data.Functor.Identity (Identity (.. ))
17
18
import Data.IORef (IORef , readIORef )
18
- import Data.Maybe (catMaybes )
19
+ import Data.Maybe (catMaybes , fromMaybe )
19
20
import Data.Traversable (for )
20
21
21
22
import Reflex
@@ -82,32 +83,33 @@ runHeadlessApp guest =
82
83
-- 'Nothing' if the guest application hasn't subscribed to this event.
83
84
mPostBuildTrigger <- readRef postBuildTriggerRef
84
85
85
- -- When there is a subscriber to the post-build event, fire the event.
86
- for_ mPostBuildTrigger $ \ postBuildTrigger ->
87
- fire [postBuildTrigger :=> Identity () ] $ pure ()
88
-
89
86
-- Subscribe to an 'Event' of that the guest application can use to
90
87
-- request application shutdown. We'll check whether this 'Event' is firing
91
88
-- to determine whether to terminate.
92
89
shutdown <- subscribeEvent result
93
90
91
+ -- When there is a subscriber to the post-build event, fire the event.
92
+ soa <- for mPostBuildTrigger $ \ postBuildTrigger ->
93
+ fire [postBuildTrigger :=> Identity () ] $ isFiring shutdown
94
+
94
95
-- The main application loop. We wait for new events and fire those that
95
96
-- have subscribers. If we detect a shutdown request, the application
96
97
-- terminates.
97
- fix $ \ loop -> do
98
+ unless ( or (fromMaybe [] soa)) $ fix $ \ loop -> do
98
99
-- Read the next event (blocking).
99
100
ers <- liftIO $ readChan events
100
101
stop <- do
101
102
-- Fire events that have subscribers.
102
103
fireEventTriggerRefs fc ers $
103
104
-- Check if the shutdown 'Event' is firing.
104
- readEvent shutdown >>= \ case
105
- Nothing -> pure False
106
- Just _ -> pure True
105
+ isFiring shutdown
107
106
if or stop
108
107
then pure ()
109
108
else loop
110
109
where
110
+ isFiring ev = readEvent ev >>= \ case
111
+ Nothing -> pure False
112
+ Just _ -> pure True
111
113
-- Use the given 'FireCommand' to fire events that have subscribers
112
114
-- and call the callback for the 'TriggerInvocation' of each.
113
115
fireEventTriggerRefs
0 commit comments