Skip to content

Commit 9577651

Browse files
committed
readme of singleassignment
1 parent 612cd14 commit 9577651

File tree

2 files changed

+50
-0
lines changed

2 files changed

+50
-0
lines changed

README.md

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -609,6 +609,30 @@ void Close()
609609
}
610610
```
611611

612+
```csharp
613+
IDisposable disposable;
614+
615+
void OnInitialize(ISubscriber<int> subscriber)
616+
{
617+
var bag = DisposableBag.CreateBuilder();
618+
619+
// calling once(or x count), you can use DisposableBag.CreateSingleAssignment to hold subscription reference.
620+
var d = DisposableBag.CreateSingleAssignment();
621+
622+
// you can invoke Dispose in handler action.
623+
// assign disposable, you can use `SetTo` and `AddTo` bag.
624+
// or you can use d.Disposable = subscriber.Subscribe();
625+
subscriber.Subscribe(_ => { d.Dispose(); }).SetTo(d).AddTo(bag);
626+
627+
disposable = bag.Build();
628+
}
629+
630+
void Close()
631+
{
632+
disposable?.Dispose();
633+
}
634+
```
635+
612636
The returned `IDisposable` value **must** be handled. If it is ignored, it will leak. However Weak reference, which is widely used in WPF, is an anti-pattern. All subscriptions should be managed explicitly.
613637

614638
You can monitor subscription count by `MessagePipeDiagnosticsInfo`. It can get from service provider(or DI).

tests/MessagePipe.Tests/DisaposableBagTest.cs

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
using FluentAssertions;
2+
using Microsoft.Extensions.DependencyInjection;
23
using System;
4+
using System.Collections.Generic;
35
using System.Linq;
46
using Xunit;
57

@@ -141,6 +143,30 @@ public void SingleAssignment()
141143
}
142144
}
143145

146+
[Fact]
147+
public void CallOnce()
148+
{
149+
var provider = TestHelper.BuildServiceProvider();
150+
151+
var p = provider.GetRequiredService<IPublisher<int>>();
152+
var s = provider.GetRequiredService<ISubscriber<int>>();
153+
154+
var d = DisposableBag.CreateSingleAssignment();
155+
156+
var list = new List<int>();
157+
d.Disposable = s.Subscribe(x =>
158+
{
159+
list.Add(x);
160+
d.Dispose();
161+
});
162+
163+
p.Publish(100);
164+
p.Publish(200);
165+
p.Publish(300);
166+
167+
list.Should().Equal(new[] { 100 });
168+
}
169+
144170
public class Disposable : IDisposable
145171
{
146172
public int Number { get; }

0 commit comments

Comments
 (0)