I am new to System.Reactive and trying to understand how to use this extension for some of the scenarios.
I have basically three components, one is creating the message and the others are the receiver of the message.
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)); }}The IMessager inherits IDisposable and the IMessager is registered as Scoped in the Program.cs file.
ComponentOne.razor and ComponentTwo.razor are look exactly like the below code
@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(); } }The MessageCreator.razor looks like:
@inject IMessager _messager;<div><button @onclick="ClickMe">ClickMe</button></div>@code { private int count = 0; private void ClickMe() { count++; _messager.Emit(count); }}And they are called in the home.razor
@page "/"<div><div><ComponentOne/></div><div><ComponentTwo/></div></div>If I click the button ClickMe on ComponentOne -> MessageCreator -> ClickMe - this increments the counter to 1. Both the components are updated with the value 1 because both are "subscribing" through OnEmit. Same goes for the ComponentTwo only with a separate instance of MessageCreator.razor.
So here's some of my questions:
Question 1: The IMessager registered with Scoped but when I tried with Transient it does not work, why? (Because ComponentOne.razor and MessageCreator.razor must get the same obejct.. I guess)
Question 2. Is there a way to unsubscribe. Let just say for certain cases the ComponentOne does not want to receive any notification?
Question 3. What I want is that a message generated from clicking on ComponentOne -> MessageCreator -> ClickMe should only receive by ComponentOne but not by ComponentTwo.(or do I have to use something other than Subjct)