Not an ID
Not an ID

Reputation: 2589

Elm: how does Mailbox work?

Say I create a Mailbox using mailbox = Signal.mailbox Action, where type Action = Blah, later I can send actions to this mailbox using Signal.send mailbox.address Blah, this allows me to listen on mailbox.signal, how so? I mean, after all, type Mailbox is just an alias of {address : Signal.Address Action, signal : Signal.Signal Action}, is it because that, in elm, there is only one signal for a certain type, so in the above scenario, I don't have to tell elm to bind mailbox.signal with mailbox.address, elm will figure out itself because of the one-to-one correspondence between the address and signal of a certain type?

Upvotes: 5

Views: 790

Answers (1)

Apanatshka
Apanatshka

Reputation: 5958

The ability for mailbox to put events you send to it into its signal is entirely based on "magic", that is, it's implemented natively (in JavaScript) and not something you could implement yourself. That's why it's a built-in in the standard libraries.

Creating a mailbox is an imperative, effectful action (shhh, don't tell anyone). So if you use:

mailbox1 = Signal.mailbox Blah
mailbox2 = Signal.mailbox Blah

those two mailboxes will be distinct. Send a message to mailbox2.address will result in a message on mailbox2.signal but not mailbox1.signal. This breaks referential transparency, which is bad, but for now it's not breaking everything. (This may go too far into a tangent, but because you need Signal for output and can't have Signal (Signal something), in practice the unmanaged effect of mailbox creation is not messing things up). This "leak" will be fixed at some point in the future. There was a proposal already but big changes are staged in different versions of the language.

Upvotes: 6

Related Questions