Misha Moroshko
Misha Moroshko

Reputation: 171351

How to get the current value of a Signal in Elm?

Is there a way to get the current value of a given signal? Or, is this something that I shouldn't want to do when writing idiomatic Elm?

Upvotes: 3

Views: 212

Answers (2)

Apanatshka
Apanatshka

Reputation: 5958

Normal code

You shouldn't want to do that when writing idiomatic Elm.
It's also not possible to get the current value of a signal. This would be a side-effecting function (returning different values at different times in the program execution), which would allow all kinds of nasty bugs to crop up. To do something with the value on a signal, you can map over the signal with Signal.map but I suspect you already know that one.

Testing

If you're asking about this for testing purposes rather than normal code, you can hack around the limitation using the technique that's used in package Apanatshka/elm-signal-extra to write tests for signal-related functions. (Note that although I'm the author of that package, kudos for the testing system should go to rgremple for conceiving of and contributing it)

Upvotes: 4

pdamoc
pdamoc

Reputation: 2923

The way I understand it, the concept of "current value" has no meaning in Elm.

Sure, if you Signal.map a function over a signal, you can say that that function will always receive the "current value" but I don't think that this is what you meant.

The idea of "current value" involves time. It involves the idea of having a "before I ask for the current value" and an "after I ask for the current value". This is something that you might find in an imperative language but Elm is declarative and as such, the concept of before and after have no meaning.

Upvotes: 2

Related Questions