-- |Description: Events Combinators
module Polysemy.Conc.Events where

import Polysemy.Conc.Interpreter.Events (EventConsumer)
import qualified Polysemy.Conc.Effect.Events as Events

-- |Pull repeatedly from the 'Events' channel, passing the event to the supplied callback.
-- Stop when the action returns @False@.
subscribeWhile ::
   e token r .
  Member (EventConsumer token e) r =>
  (e -> Sem r Bool) ->
  Sem r ()
subscribeWhile :: (e -> Sem r Bool) -> Sem r ()
subscribeWhile e -> Sem r Bool
action =
  Sem (Consume e : r) () -> Sem r ()
forall e token (r :: [Effect]).
Member (Scoped (EventToken token) (Consume e)) r =>
InterpreterFor (Consume e) r
Events.subscribe @e @token Sem (Consume e : r) ()
spin
  where
    spin :: Sem (Consume e : r) ()
spin =
      Sem (Consume e : r) Bool
-> Sem (Consume e : r) () -> Sem (Consume e : r) ()
forall (m :: * -> *). Monad m => m Bool -> m () -> m ()
whenM (Sem r Bool -> Sem (Consume e : r) Bool
forall (e :: Effect) (r :: [Effect]) a. Sem r a -> Sem (e : r) a
raise (Sem r Bool -> Sem (Consume e : r) Bool)
-> (e -> Sem r Bool) -> e -> Sem (Consume e : r) Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. e -> Sem r Bool
action (e -> Sem (Consume e : r) Bool)
-> Sem (Consume e : r) e -> Sem (Consume e : r) Bool
forall (m :: * -> *) a b. Monad m => (a -> m b) -> m a -> m b
=<< Sem (Consume e : r) e
forall e (r :: [Effect]). MemberWithError (Consume e) r => Sem r e
Events.consume) Sem (Consume e : r) ()
spin

-- |Pull repeatedly from the 'Events' channel, passing the event to the supplied callback.
subscribeLoop ::
   e token r .
  Member (EventConsumer token e) r =>
  (e -> Sem r ()) ->
  Sem r ()
subscribeLoop :: (e -> Sem r ()) -> Sem r ()
subscribeLoop e -> Sem r ()
action =
  Sem (Consume e : r) () -> Sem r ()
forall e token (r :: [Effect]).
Member (Scoped (EventToken token) (Consume e)) r =>
InterpreterFor (Consume e) r
Events.subscribe @e @token (Sem (Consume e : r) () -> Sem (Consume e : r) ()
forall (f :: * -> *) a b. Applicative f => f a -> f b
forever (Sem r () -> Sem (Consume e : r) ()
forall (e :: Effect) (r :: [Effect]) a. Sem r a -> Sem (e : r) a
raise (Sem r () -> Sem (Consume e : r) ())
-> (e -> Sem r ()) -> e -> Sem (Consume e : r) ()
forall b c a. (b -> c) -> (a -> b) -> a -> c
. e -> Sem r ()
action (e -> Sem (Consume e : r) ())
-> Sem (Consume e : r) e -> Sem (Consume e : r) ()
forall (m :: * -> *) a b. Monad m => (a -> m b) -> m a -> m b
=<< Sem (Consume e : r) e
forall e (r :: [Effect]). MemberWithError (Consume e) r => Sem r e
Events.consume))