System.Reactive Subject技术疑问:作用域、取消订阅与消息隔离
场景说明
我是System.Reactive的新手,搭建了包含三个组件的场景:一个消息创建组件,另外两个为消息接收组件,代码实现如下:
Messager 类(实现 IMessager 接口)
public class Messager : IMessager { private readonly Subject<int> _subject = new(); private readonly List<IDisposable> _disposables = []; public void Dispose() { _subject?.Dispose(); foreach (var eachDisposable in _disposables) { eachDisposable?.Dispose(); } } public void Emit(int value) { _subject.OnNext(value); } public void OnEmit(Action<int> action) { _disposables.Add(_subject.Subscribe(action)); } }
IMessager 继承自 IDisposable,并在 Program.cs 中注册为 Scoped 服务。
ComponentOne.razor 与 ComponentTwo.razor
@inject IMessager _messager; <div> <span>@value</span> <div> <MessageCreator/> </div> </div> @code { private int value; protected override void OnInitialized() { base.OnInitialized(); _messager.OnEmit(Action); } private void Action(int value) { this.value = value; StateHasChanged(); } }
MessageCreator.razor
@inject IMessager _messager; <div> <button @onclick="ClickMe">ClickMe</button> </div> @code { private int count = 0; private void ClickMe() { count++; _messager.Emit(count); } }
Home.razor
@page "/" <div> <div> <ComponentOne/> </div> <div> <ComponentTwo/> </div> </div>
当前场景中,点击 ComponentOne 内的 MessageCreator 按钮时,两个组件都会更新数值,现针对以下问题解答:
问题解答
1. 为何 IMessager 注册为 Scoped 时功能正常,改为 Transient 则无法工作?
Scoped 服务在同一个请求/会话周期内是单实例,ComponentOne、ComponentTwo 和 MessageCreator 注入的是同一个 Messager 对象,所有组件共享同一个 Subject,消息能正常传递。而 Transient 服务每次注入都会生成新实例:ComponentOne 内部的 MessageCreator 用的是独立的 Messager,ComponentTwo 用的是另一个完全无关的实例,两者的 Subject 没有关联,自然收不到对方的消息。
2. 是否存在取消订阅 Subject 的方法,例如让 ComponentOne 不再接收消息通知?
当然有。Subscribe 方法返回的 IDisposable 实例就是用来取消订阅的。你可以调整代码让组件自己管理订阅:
修改 ComponentOne/Two 的代码示例:
@inject IMessager _messager; @implements IDisposable <div> <span>@value</span> <div> <MessageCreator/> </div> </div> @code { private int value; private IDisposable? _subscription; protected override void OnInitialized() { base.OnInitialized(); // 保存订阅实例,方便后续取消 _subscription = _subject.Subscribe(Action); // 如果要保留原Messager的OnEmit方法,可以修改它返回IDisposable,让组件自行存储 // _subscription = _messager.OnEmit(Action); } private void Action(int value) { this.value = value; StateHasChanged(); } public void Dispose() { // 组件销毁时取消订阅 _subscription?.Dispose(); } }
你也可以在 Messager 内部维护订阅列表,提供带标识的取消订阅方法,但组件自行管理订阅会更灵活。
3. 如何实现点击 ComponentOne 内的 MessageCreator 按钮时,仅 ComponentOne 接收消息,而 ComponentTwo 不接收?是否需要替换 Subject?
不需要替换 Subject,有两种常用实现方式:
方式一:按标识过滤消息
给消息带上发送方标识,组件只处理匹配自己标识的消息:
- 修改 Messager 的方法,支持标识参数:
public void Emit(int value, string senderId) { _subject.OnNext((value, senderId)); } public IDisposable OnEmit(Action<int> action, string targetId) { return _subject.Where(msg => msg.senderId == targetId) .Select(msg => msg.value) .Subscribe(action); }
- 组件初始化时生成唯一标识,传递给内部的 MessageCreator:
ComponentOne 代码调整:
@inject IMessager _messager; @implements IDisposable @code { private string _componentId = Guid.NewGuid().ToString(); private IDisposable? _subscription; protected override void OnInitialized() { _subscription = _messager.OnEmit(Action, _componentId); } }
MessageCreator 新增参数接收标识:
[Parameter] public string SenderId { get; set; } = string.Empty; private void ClickMe() { count++; _messager.Emit(count, SenderId); }
ComponentOne 引用 MessageCreator 时传参:<MessageCreator SenderId="@_componentId"/>
方式二:使用多频道 Subject
在 Messager 里维护字典,每个组件对应独立的 Subject 频道:
private Dictionary<string, Subject<int>> _subjects = new(); public string CreateChannel() { var id = Guid.NewGuid().ToString(); _subjects[id] = new Subject<int>(); return id; } public void Emit(int value, string channelId) { if (_subjects.TryGetValue(channelId, out var subject)) { subject.OnNext(value); } } public IDisposable SubscribeToChannel(Action<int> action, string channelId) { if (_subjects.TryGetValue(channelId, out var subject)) { return subject.Subscribe(action); } return Disposable.Empty; }
组件创建时生成专属频道ID,订阅该频道,MessageCreator 用对应频道发送消息即可。
内容的提问来源于stack exchange,提问作者riki

