Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add extension function on observable to ignore OnComplete events #1135

Merged
merged 3 commits into from
Jul 8, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,35 @@ public StateObservableExtensionsTest()
EntityState.Map<NumericEntityState>(e.New)));
}

[Fact]
public void TestThrottleShouldNotCallActionUsingIngoreOnCompleteWhenSubjectCompleted()
{
bool isCalled = false;

_subject.Where(n => n?.New?.State == "off").IgnoreOnComplete().Throttle(TimeSpan.FromSeconds(1), _testScheduler).Subscribe(_ => { isCalled = true;});

_subject.OnNext(new StateChange(new Entity(new Mock<IHaContext>().Object, ""), new EntityState { State = "on" }, new EntityState { State = "off" }));

_subject.OnCompleted();

isCalled.Should().BeFalse();
}

[Fact]
public void TestThrottleShouldCallActionUsingIngoreOnCompleteInNormalOperation()
{
bool isCalled = false;

_subject.Where(n => n?.New?.State == "off").IgnoreOnComplete().Throttle(TimeSpan.FromSeconds(1), _testScheduler).Subscribe(_ => { isCalled = true;});

_subject.OnNext(new StateChange(new Entity(new Mock<IHaContext>().Object, ""), new EntityState { State = "on" }, new EntityState { State = "off" }));

_testScheduler.AdvanceBy(TimeSpan.FromSeconds(2).Ticks);
_subject.OnCompleted();

isCalled.Should().BeTrue();
}

[Fact]
public void TestThatWhenStateIsForDoesNotCallActionWhenCompleted()
{
Expand Down
11 changes: 11 additions & 0 deletions src/HassModel/NetDeamon.HassModel/StateObservableExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,17 @@ namespace NetDaemon.HassModel;
/// </summary>
public static class StateObservableExtensions
{
/// <summary>
/// Ignores the OnCompletion event of the observable
/// </summary>
/// <remarks>
/// This can be used in combination with Throttle() to avoid events to be emitted when the
/// observable is completed (eg because the app is stopped). Use IgnoreOnComplete(). before
/// Throttle() to make sure Throttle will not send events when the app is stopping.
/// </remarks>
public static IObservable<T> IgnoreOnComplete<T>(this IObservable<T> source)
=> Observable.Create<T>(observer => source.Subscribe(observer.OnNext, observer.OnError));

/// <summary>
/// Waits for an EntityState to match a predicate for the specified time
/// </summary>
Expand Down
Loading