reflex
reflex copied to clipboard
Add a utility for creating events based on STM actions
Feel free to reject this if it's too specific a use case, as it's just a thin wrapper around newEventWithLazyTriggerWithOnComplete
, but I found it useful for creating events which interface with external global triggers without leaking memory.
Note that I didn't include the OnComplete
functionality since I didn't have a need for it. ~~However, maybe it makes sense to have since it could work nicely with the transactional part of STM.~~ Edit: I realized this wouldn't work since triggering the reflex event inside the transaction doesn't make sense.
@kmicklas Just curious - what do you use this for (i.e., application use case)?
@srid My use case is listening to global Android events. You can have Java call into Haskell with JNI, but to trigger a reflex event created with newTriggerEvent
you would need access to the IO ()
trigger, which may not have even been created yet.
There are several non-ideal solutions I can think of:
- You could reimplement a global "event listener" stack like in classic GUI frameworks. I think you would still need to use
newEventWithLazyTriggerWithOnComplete
to avoid leaking memory when the event is garbage collected though. - Reflex-dom achieves this by creating its event triggers before the Android activity has finished initializing, but this limits you to a static set of known events.
- You could create the event at the top level of your app with
newTriggerEvent
, with the trigger reading on a single global channel which the JNI handler writes to, and then pass this event down to wherever you need it in your app. This works but is not composable.
My solution is to have the JNI handler write to a broacast TChan
, which will simply drop the value if there are no readers (created with dupTChan
). With this function, when the event is torn down, the forked loop will terminate and the duplicated TChan
should be garbage collected.
I want to study the code a bit more, but your use case seems equally interesting and possibly a way to simplify the Android logic in Reflex-DOM which, as you say, is rather tricky.