reactive-banana
reactive-banana copied to clipboard
Hook into event/behavior life cycle?
Hello! Is it possible to detect when an Event is no longer relevant to the network (garbage collected)? My use-case is killing a thread that's spawned in a MomentIO computation. I can provide more details if necessary.
Thanks!
This is currently not part of the API, but I think it should be possible to implement. Could you provide a short overview of your use case for why this is a good thing to have? Note that the whole garbage collection / finalizer thing can be rather tricky, so it's always a good idea to avoid it if possible.
Sure, I was playing around with implementing a sort of arcade, in which some minigames had a concept of a timer and others did not.
Rather than have a global ticking thread, I wanted to spawn a background thread in the Moment that some relevant game is switched to, and kill it when it's no longer necessary to have a tick event:
makeTickEvent :: MomentIO (Event ())
makeTickEvent = do
(etick, tick) <- newEvent
tid <- liftIO . forkIO . forever $ do
threadDelay 1000000
tick ()
-- Here I want to attach a finalizer to `etick` that kills thread `tid`
pure etick
While this is obviously a fine thing to want to do, can you explain why you'd want to do it without a global tick event? It's easier to add new features if it's clear that they enable functionality that is otherwise impossible.
It's just the first solution that came to mind, and it'd actually make the code a bit cleaner.
The real type signature for makeTickEvent is
makeTickEvent
:: Int -- Initial delay
-> Event (Int -> Int) -- Change delay
-> MomentIO (Event ())
So, the ticks can be sped up or slowed down (in some games) by pressing some keys. If I had to use a global ticking event:
- I'd have an additional behavior to determine whether or not speeding up/slowing down events is possible
- I'd have to reset the delay to the default when switching
- I couldn't guarantee that a tick happens in the first moment of a game's existence
None of these are really game-changers (ha), so a global tick event will actually be fine for my purposes :)
However, now I'm imagining some polling behavior that is truly costly to perform, like periodically hitting some rate-limited API, where only paying for what you use is much more desirable.