Skip to content

Commit 0315ea1

Browse files
authored
Add extension function on observable to ignore OnComplete events (#1135)
* Adds the possibility to ignore the OnComplete event on subscriptions * some fixes * fix after comments
1 parent 11db230 commit 0315ea1

File tree

2 files changed

+40
-0
lines changed

2 files changed

+40
-0
lines changed

src/HassModel/NetDaemon.HassModel.Tests/StateObservableExtensionsTest.cs

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,35 @@ public StateObservableExtensionsTest()
2020
EntityState.Map<NumericEntityState>(e.New)));
2121
}
2222

23+
[Fact]
24+
public void TestThrottleShouldNotCallActionUsingIngoreOnCompleteWhenSubjectCompleted()
25+
{
26+
bool isCalled = false;
27+
28+
_subject.Where(n => n?.New?.State == "off").IgnoreOnComplete().Throttle(TimeSpan.FromSeconds(1), _testScheduler).Subscribe(_ => { isCalled = true;});
29+
30+
_subject.OnNext(new StateChange(new Entity(new Mock<IHaContext>().Object, ""), new EntityState { State = "on" }, new EntityState { State = "off" }));
31+
32+
_subject.OnCompleted();
33+
34+
isCalled.Should().BeFalse();
35+
}
36+
37+
[Fact]
38+
public void TestThrottleShouldCallActionUsingIngoreOnCompleteInNormalOperation()
39+
{
40+
bool isCalled = false;
41+
42+
_subject.Where(n => n?.New?.State == "off").IgnoreOnComplete().Throttle(TimeSpan.FromSeconds(1), _testScheduler).Subscribe(_ => { isCalled = true;});
43+
44+
_subject.OnNext(new StateChange(new Entity(new Mock<IHaContext>().Object, ""), new EntityState { State = "on" }, new EntityState { State = "off" }));
45+
46+
_testScheduler.AdvanceBy(TimeSpan.FromSeconds(2).Ticks);
47+
_subject.OnCompleted();
48+
49+
isCalled.Should().BeTrue();
50+
}
51+
2352
[Fact]
2453
public void TestThatWhenStateIsForDoesNotCallActionWhenCompleted()
2554
{

src/HassModel/NetDeamon.HassModel/StateObservableExtensions.cs

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,17 @@ namespace NetDaemon.HassModel;
77
/// </summary>
88
public static class StateObservableExtensions
99
{
10+
/// <summary>
11+
/// Ignores the OnCompletion event of the observable
12+
/// </summary>
13+
/// <remarks>
14+
/// This can be used in combination with Throttle() to avoid events to be emitted when the
15+
/// observable is completed (eg because the app is stopped). Use IgnoreOnComplete(). before
16+
/// Throttle() to make sure Throttle will not send events when the app is stopping.
17+
/// </remarks>
18+
public static IObservable<T> IgnoreOnComplete<T>(this IObservable<T> source)
19+
=> Observable.Create<T>(observer => source.Subscribe(observer.OnNext, observer.OnError));
20+
1021
/// <summary>
1122
/// Waits for an EntityState to match a predicate for the specified time
1223
/// </summary>

0 commit comments

Comments
 (0)