Created
June 3, 2021 16:07
-
-
Save neuecc/0e9a9999b031e00de37f3c058efc1937 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// MagicOnion(similar as SignalR, realtime event framework for .NET and Unity) | |
public class UnityConnectionHub : StreamingHubBase<IUnityConnectionHub, IUnityConnectionHubReceiver>, IUnityConnectionHub | |
{ | |
readonly IPublisher<Guid, UnitEventData> eventPublisher; | |
readonly IPublisher<Guid, ConnectionClose> closePublisher; | |
Guid id; | |
| |
public UnityConnectionHub(IPublisher<Guid, UnitEventData> eventPublisher, IPublisher<Guid, ConnectionClose> closePublisher) | |
{ | |
this.eventPublisher = eventPublisher; | |
this.closePublisher = closePublisher; | |
} | |
| |
override async ValueTask OnConnected() | |
{ | |
this.id = Guid.Parse(Context.Headers["id"]); | |
} | |
| |
override async ValueTask OnDisconnected() | |
{ | |
this.closePublisher.Publish(id, new ConnectionClose()); // publish to browser(Blazor) | |
} | |
| |
// called from Client(Unity) | |
public Task<UnityEventData> SendEventAsync(UnityEventData data) | |
{ | |
this.eventPublisher.Publish(id, data); // publish to browser(Blazor) | |
} | |
} | |
| |
// Blazor | |
public partial class BlazorPage : ComponentBase, IDisposable | |
{ | |
[Parameter] | |
public Guid ID { get; set; } | |
| |
[Inject] | |
ISubscriber<Guid, UnitEventData> UnityEventSubscriber { get; set; } | |
| |
[Inject] | |
ISubscriber<Guid, ConnectionClose> ConnectionCloseSubscriber { get; set; } | |
| |
IDisposable subscription; | |
| |
protected override void OnInitialized() | |
{ | |
// receive event from MagicOnion(that is from Unity) | |
var d1 = UnityEventSubscriber.Subscribe(ID, x => | |
{ | |
// do anything... | |
}); | |
| |
var d2 = ConnectionCloseSubscriber.Subscribe(ID, _ => | |
{ | |
// show disconnected thing to view... | |
subscription?.Dispose(); // and unsubscribe events. | |
}); | |
| |
subscription = DisposableBag.Create(d1, d2); // combine disposable. | |
} | |
public void Dispose() | |
{ | |
// unsubscribe event when browser is closed. | |
subscription?.Dispose(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment