Dynamically Creating Elm Subscriptions

Cleaning up the Model

billperegoy
im-becoming-functional
2 min readMar 28, 2017

--

Some Ideas for Improvement

In my previous post, I made an attempt to use Elm subscriptions to create message elements that would disappear after a prescribed timeout period. Unfortunately, this code did not work as expected. I was depending upon the Time.every subscription, hoping the the “every” period for each subscription would start at the subscription creation time. It turns out that the start of the “every” period seems to always coincide with the time the application started, so I didn’t get the behavior I expected.

Because I was expecting this behavior, I ended up storing the subscriptions in the model. I got some great feedback on this post, including some feedback indicating that it wasn’t considered good practice to store functions or subscriptions in the model.

There’s an easy fix for this. I can simply use a map function to convert the list of flash elements into a list of subscriptions. In order to do this, I only needed a few changes to my code.

Modifying the Model

First, I added a duration to the record describing a flash element.

I also removed the subscriptions from the model.

Updating the CreateFlashElement Action

Since we no longer store subscriptions in the model, we can now greatly simplify the Create FlashElement update action. There’s no longer a need to add to the subscription list. So we can reduce this action to this much simpler version.

Modifying the Subscriptions

Finally, I modified the subscriptions function to build the subscription list from the list of flash elements.

You’ll see that here I now use a map function to convert a list of flash elements into a list of subscriptions. This list is then used to create the subscriptions that are supplied to the main application.

Summary

This approach feels cleaner and more truer to the Elm architecture than the previous one. We no longer store subscriptions in the model and use a more functional approach to building the subscription list.

One additional side-effect of this change is that the subscriptions are cleaned up. The previous version had a problem where older subscriptions corresponding to already removed elements never went away. With this version, the subscription list only contains entries corresponding to active elements.

You can find a working copy of this code in this git release.

--

--

billperegoy
im-becoming-functional

Polyglot programmer exploring the possibilities of functional programming.