Skip to content

Commit

Permalink
Made Signal a newtype, so it's easier to pass around (#4)
Browse files Browse the repository at this point in the history
  • Loading branch information
robertdp authored May 20, 2020
1 parent ecf232f commit 5f0274a
Showing 1 changed file with 31 additions and 14 deletions.
45 changes: 31 additions & 14 deletions src/Wire/Signal.purs
Original file line number Diff line number Diff line change
Expand Up @@ -6,27 +6,44 @@ import Effect.Ref as Ref
import Wire.Event (Event)
import Wire.Event as Event

type Signal a
= { event :: Event a
, modify :: (a -> a) -> Effect Unit
, read :: Effect a
, write :: a -> Effect Unit
, cancel :: Effect Unit
}

create :: forall a. a -> Effect (Signal a)
newtype Signal a
= Signal
{ event :: Event a
, modify :: (a -> a) -> Effect Unit
, read :: Effect a
, write :: a -> Effect Unit
}

create :: forall a. a -> Effect { signal :: Signal a, cancel :: Effect Unit }
create init = do
value <- Ref.new init
inner <- Event.create
let
read = Ref.read value
read' = Ref.read value

write a = modify (const a)
write' a = modify' (const a)

modify f = Ref.modify f value >>= inner.push
modify' f = Ref.modify f value >>= inner.push

event =
event' =
Event.makeEvent \emit -> do
Ref.read value >>= emit
Event.subscribe inner.event emit
pure { event, read, write, modify, cancel: inner.cancel }

signal = Signal { event: event', read: read', write: write', modify: modify' }
pure { signal, cancel: inner.cancel }

event :: forall a. Signal a -> Event a
event (Signal s) = s.event

read :: forall a. Signal a -> Effect a
read (Signal s) = s.read

write :: forall a. a -> Signal a -> Effect Unit
write a (Signal s) = s.write a

modify :: forall a. (a -> a) -> Signal a -> Effect Unit
modify f (Signal s) = s.modify f

distinct :: forall a. Eq a => Signal a -> Signal a
distinct (Signal s) = Signal s { event = Event.distinct s.event }

0 comments on commit 5f0274a

Please sign in to comment.