Ido Ran
Ido Ran

Reputation: 11374

When Elm Html.Program calls subscriptions

I've found a possible answer to this question in a Google Group but I'll like to know if it's correct and add a follow-up question if it is correct.

The answer there is

Every time the global update function in your app runs for any reason, the global subscriptions object is reevaluated as well, and effect managers receive the new list of current subscriptions

If any time the model is changed subscriptions get called what is the effect on subscriptions such as Time.every second taken from Time Effect Elm Guide - is that means the timer get reset when the model changes? What if that was Time.every minute - if the model changes 20 seconds after it starts will it fire in 60 - 20 = 40 seconds or will it fire in 1 minute?

Upvotes: 3

Views: 323

Answers (2)

wintvelt
wintvelt

Reputation: 14101

TLDR; It will fire in 1 minute, unless you turn your subscription off and on during the first minute

Every time your update runs, the subscriptions function will run too. The subscriptions function essentially is a list of things you want your app to subscribe to.

In the example you have a subscription that generates a Tick message every 60 seconds.

The behavior you may expect is:

  • T= 0s: The first time subscriptions runs, you start your subscription to "receive Tick message every 60 seconds".
  • T= between 0 AND 60s: As long as that particular subscription remains ON, it doesn't matter how often your update function runs. subscriptions will be run, but as long as your particular subscription to the Tick remains ON, things are fine.
  • T= 60s: You receive a Tick message from your subscription, which in turn will fire update to be called.
  • T= 60s: subscriptions will run again (because of previous call to update)

What could be interesting is what happens if the subscription to Tick is canceled along the way and then reinstated:

  • T= 0: subscription to Tick
  • T= 20s: suppose something changes in the model, causing subscription to Tick to be canceled
  • T= 40s: some other change in model, causing subscription to Tick to be turned on again
  • T= 100s: Tick message is fired, and passed to update function
  • T= 100s: subscriptions will run again

Upvotes: 1

Shaun the Sheep
Shaun the Sheep

Reputation: 22742

You can check when update and subscriptions are called by adding a Debug.log statement to each. The subscriptions function is called first at the start (since the messages which will be sent to update may depend on it) and also after each call to update.

The timer interval seems to be unaffected by subsequent calls to subscriptions. For example, if you use the elm clock example, change the subscription to

Time.every (10*Time.second) Tick

and add a button to the view which resets the model value to 0, you will see that the tick still takes place at regular 10s intervals, no matter when you click the button.

Upvotes: 3

Related Questions