Skip to content

Commit

Permalink
Merge pull request #587 from lukaszkrzywizna/use-elmish-stable
Browse files Browse the repository at this point in the history
Making UseElmish's dispatch function stable.
  • Loading branch information
Zaid-Ajaj authored Nov 21, 2023
2 parents e508a7a + 42f4e0a commit f25422d
Showing 1 changed file with 13 additions and 3 deletions.
16 changes: 13 additions & 3 deletions Feliz.UseElmish/UseElmish.fs
Original file line number Diff line number Diff line change
Expand Up @@ -30,11 +30,20 @@ module private Util =
// Keep track of messages are that dispach from the initial No-Op dispatch
// And dispatch them after the Elmish program has subscribed using the "real" dispatch
let queuedMessages = ResizeArray<'Msg>()

// To assure that dispatch function is stable (for example for memo).
// We need to store external reference to final dispatch function assuring that initial version
// will forward to it at some point.
let mutable finalDispatch = None

let mutable state, cmd =
let mutable model, cmd = Program.init program arg
// Initial dispatch is a No-Op before the Elmish program has subscribed
// So here we store the messages and dispatch them after the Elmish program has subscribed
let initialDispatch (msg: 'Msg) = queuedMessages.Add msg
let initialDispatch (msg: 'Msg) =
match finalDispatch with
| Some dispatch -> dispatch msg
| None -> queuedMessages.Add msg
let subscribed = false
(model, initialDispatch, subscribed, queuedMessages), cmd

Expand Down Expand Up @@ -78,9 +87,10 @@ module private Util =
program
|> Program.map mapInit mapUpdate id id id mapTermination
|> Program.withSetState (fun model dispatch ->
let (oldModel, _, _, _) = state
let (oldModel, initialDispatch, _, _) = state
let subscribed = true
state <- model, dispatch, subscribed, queuedMessages
finalDispatch <- Some dispatch
state <- model, initialDispatch, subscribed, queuedMessages
// Skip re-renders if model hasn't changed
if not(obj.ReferenceEquals(model, oldModel)) then
callback())
Expand Down

0 comments on commit f25422d

Please sign in to comment.