Fork me on GitHub

How ok is in nowadays to create and deref a subscription for a one-time use in an event handler?

Braden Shepherdson15:11:47

consider putting the sub's calculation in a helper function and running that over the database? or is it at the end of a complex chain of subs?


@mbertheau I think that generally it should be avoided. What is the use case? I think that some alternatives for this would be to just grab whatever value the subscription returns from the db itself - or it might be better to pass the subscription value to the event handler from the view.

(defn view
  (let [sub-value @(subscribe :some-sub)]
    (dispatch [:some-event sub-value]))
or what Braden said:
(defn computation [db] (do-stuff db))
(reg-sub :some-sub (fn [db _] (computation db))
(reg-event :some-event (fn [db _] (let [computed-value (computation db)] ...))
I've done both of these things in the past and would actually be interested in learning which one is better 😛 or if there is some other even better solution


Yeah well I know that subscriptions aren't (weren't?) intended to be used like that. I just wonder what the current implications of such an approach might be - memory and cpu-wise. I assume because subscriptions are cached the additional cpu load would be negligible, but maybe some memory won't be freed.


@mbertheau you could use the inject-sub cofx from re-frame utils


@danieleneal Interesting. Thanks for the pointer!


@mbertheau i find myself running into this all the time, particularly with much larger apps. often i have a very nicely defined set of subs, and i like the idea of just using a sub as a read-only view in a handler. i don’t like extracting the sub into a fn and reusing it elsewhere because it introduces namespace dependencies (and is less svelte imo). i wish there was some sort of first class mechanism for this, as it just feels so powerful to say “give me this thing” without having to say how or where.


then again, all it’s really buying me to use inject sub is a global namespace registry. it’s no different than passing around functions that query a db (such as with datomic).


(come to think of it, registered subs in a registry are kind of akin to datomic’s “installed queries”. they’re just “built-in” and anyone can use them once registered the first time, no require required ;))