Skip to content

Commit

Permalink
Merge d8956e4 into fb662f7
Browse files Browse the repository at this point in the history
  • Loading branch information
helto4real committed Jan 2, 2021
2 parents fb662f7 + d8956e4 commit 79ca9fa
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 2 deletions.
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
using System;
using System.Reactive.Linq;
using System.Threading;

namespace NetDaemon.Common.Reactive
{
Expand Down Expand Up @@ -43,16 +44,24 @@ public static IObservable<(EntityState Old, EntityState New)> NDWaitForState(thi
/// </summary>
/// <param name="observable">Extended object</param>
/// <param name="timeout">The time to wait before timeout.</param>
public static (EntityState Old, EntityState New)? NDFirstOrTimeout(this IObservable<(EntityState Old, EntityState New)> observable, TimeSpan timeout)
/// <param name="token">Provide token to cancel early</param>
public static (EntityState Old, EntityState New)? NDFirstOrTimeout(this IObservable<(EntityState Old, EntityState New)> observable, TimeSpan timeout, CancellationToken? token = null)
{
try
{
return observable.Timeout(timeout).Take(1).Wait();
if (token is null)
return observable.Timeout(timeout).Take(1).Wait();
else
return observable.Timeout(timeout).Take(1).RunAsync(token.Value).Wait();
}
catch (TimeoutException)
{
return null;
}
catch (OperationCanceledException)
{
return null;
}
}
}
}
20 changes: 20 additions & 0 deletions tests/NetDaemon.Daemon.Tests/Reactive/RxAppTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -482,6 +482,26 @@ public async Task NDFirstOrTimeOutShouldReturnCorrectNullOnTimeout()
Assert.Null(result);
}

[Fact]
public async Task NDFirstOrTimeOutShouldReturnCorrectNullOnCancel()
{
// ARRANGE
await InitializeFakeDaemon().ConfigureAwait(false);
(EntityState Old, EntityState New)? result = null;
using CancellationTokenSource _cancelSource = new(10);

// ACT
DefaultDaemonRxApp.Entity("binary_sensor.pir")
.StateChanges
.Subscribe(_ => result = DefaultDaemonRxApp.Entity("binary_sensor.pir2").StateChanges.NDFirstOrTimeout(TimeSpan.FromMilliseconds(300), _cancelSource.Token));
DefaultHassClientMock.AddChangedEvent("binary_sensor.pir", "off", "on");

await RunFakeDaemonUntilTimeout().ConfigureAwait(false);

// ASSERT
Assert.Null(result);
}

[Fact]
public void DelayShouldCancelWithToken()
{
Expand Down

0 comments on commit 79ca9fa

Please sign in to comment.