@@ -3,7 +3,9 @@ namespace Fabulous.Tests
33open Fabulous
44open NUnit.Framework
55
6- type CmdTestsMsg = NewValue of int
6+ type CmdTestsMsg =
7+ | NewValue of int
8+ | NewValues of int list
79
810module CmdTestsHelper =
911 let execute dispatch ( cmd : Cmd < 'msg >) =
@@ -149,3 +151,64 @@ type ``Cmd tests``() =
149151 Assert.AreEqual( 2 , messageCount)
150152 Assert.AreEqual( Some( NewValue 2 ), actualValue)
151153 }
154+
155+ [<Test>]
156+ member _. ``Cmd.batchedThrottle dispatches all undispatched values on interval expiry`` () =
157+ async {
158+ let mutable messageCount = 0
159+ let mutable dispatched = [] // records dispatched messages latest first
160+
161+ let dispatch msg =
162+ messageCount <- messageCount + 1
163+ dispatched <- msg :: dispatched
164+
165+ let batchedThrottleCmd = Cmd.batchedThrottle 100 NewValues
166+
167+ batchedThrottleCmd 1 |> CmdTestsHelper.execute dispatch
168+ batchedThrottleCmd 2 |> CmdTestsHelper.execute dispatch
169+ batchedThrottleCmd 3 |> CmdTestsHelper.execute dispatch
170+ batchedThrottleCmd 4 |> CmdTestsHelper.execute dispatch
171+
172+ do ! Async.Sleep 200 // Wait longer than the throttle interval
173+
174+ // All three values should have been dispatched
175+ Assert.AreEqual( 2 , messageCount)
176+ Assert.AreEqual([ NewValues [ 2 ; 3 ; 4 ]; NewValues [ 1 ] ], dispatched)
177+ }
178+
179+ [<Test>]
180+ member _. ``Cmd.batchedThrottle dispatches messages immediately if interval not expired`` () =
181+ async {
182+ let mutable messageCount = 0
183+ let mutable dispatched = [] // records dispatched messages latest first
184+
185+ let dispatch msg =
186+ messageCount <- messageCount + 1
187+ dispatched <- msg :: dispatched
188+
189+ let batchedThrottleCmd = Cmd.batchedThrottle 100 NewValues
190+
191+ batchedThrottleCmd 1 |> CmdTestsHelper.execute dispatch
192+ batchedThrottleCmd 2 |> CmdTestsHelper.execute dispatch
193+
194+ // Only the first value should have been dispatched immediately
195+ Assert.AreEqual( 1 , messageCount)
196+ Assert.AreEqual([ NewValues[ 1 ] ], dispatched)
197+
198+ (* Wait for longer than twice the throttle interval,
199+ giving second value time to dispatch and elapsing time until next dispatch *)
200+ do ! Async.Sleep 210
201+
202+ batchedThrottleCmd 3 |> CmdTestsHelper.execute dispatch
203+ batchedThrottleCmd 4 |> CmdTestsHelper.execute dispatch
204+
205+ // Second value should have dispatched delayed, third immediately
206+ Assert.AreEqual( 3 , messageCount)
207+ Assert.AreEqual([ NewValues[ 3 ]; NewValues[ 2 ]; NewValues[ 1 ] ], dispatched)
208+
209+ do ! Async.Sleep 110 // Wait longer than the throttle interval
210+
211+ // All values should have been dispatched eventually
212+ Assert.AreEqual( 4 , messageCount)
213+ Assert.AreEqual([ NewValues[ 4 ]; NewValues[ 3 ]; NewValues[ 2 ]; NewValues[ 1 ] ], dispatched)
214+ }
0 commit comments