When do Elmish subs get disposed, if at all?

137 views Asked by At

From the Elmish docs:

open Elmish
open Fable.Core

let timer initial =
    let sub dispatch =
        JS.setInterval
            (fun _ ->
                dispatch (Tick DateTime.Now)
            )
            1000
            |> ignore
    Cmd.ofSub sub

Program.mkSimple init update (fun model _ -> printf "%A\n" model)
|> Program.withSubscription timer
|> Program.run

If this were part of a more complex app, it would be good for the setInterval to be cancelled if the component is unmounted.

With React hooks, this is part of the component life-cycle.

I am wondering how this works in Elmish?

1

There are 1 answers

0
Durdsoft On

If you’re using Feliz.useElmish and implement IDisposable on the ’State model, it will be called on unmount. See the source here: https://github.com/Zaid-Ajaj/Feliz/blob/77602c196b55f19a17c57157415e2a75b7d09ad0/Feliz.UseElmish/UseElmish.fs#L39

Looking at the sources, it doesn’t appear to be implemented at the top level in elmish react. You’d have to manually implement by having a parent component call dispose on the child at the appropriate time. In your above code snippet, it wouldn’t make sense per se because it is the only part of the application.

This is also getting addressed in the next version of fable/ elmish: https://fable.io/blog/2022/2022-10-13-use-elmish.html