Created
September 27, 2017 05:21
-
-
Save xtellurian/d66e93210629c7ea605b544021d8da63 to your computer and use it in GitHub Desktop.
Base Class ViewModel (using Fresh MVVM) for working with NFC
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
using System; | |
using System.Collections.Generic; | |
using System.Linq; | |
using System.Text; | |
using System.Threading; | |
using System.Threading.Tasks; | |
using bmx.Contract; | |
using bmx.Contract.EventArgs; | |
namespace bmx.ViewModels | |
{ | |
abstract class NfcViewModel : ViewModelBase | |
{ | |
protected INfcService NfcService { get; set; } | |
public override void Init(object initData) | |
{ | |
NfcService = Resolve<INfcService>(); | |
base.Init(initData); | |
} | |
private CancellationTokenSource _source = new CancellationTokenSource(); | |
protected override void ViewIsAppearing(object sender, EventArgs e) | |
{ | |
_source.Cancel(); | |
_source = new CancellationTokenSource(); | |
NfcService.NfcFound -= HandleNfc; | |
NfcService.NfcFound += HandleNfc; | |
base.ViewIsAppearing(sender, e); | |
} | |
protected override void ViewIsDisappearing(object sender, EventArgs e) | |
{ | |
base.ViewIsDisappearing(sender, e); | |
Task.Delay(500, _source.Token) | |
.ContinueWith((task, obj) => HandleDisconnect(task.IsCanceled), null); | |
} | |
private void HandleDisconnect(bool cancelled) // disconnect event if navigated away | |
{ | |
// this method is required becuase reading an NFC tag 'temporarily' makes the view dissappear and appear, meaning we can't naiivly disconnect the event | |
if (!cancelled) | |
{ | |
NfcService.NfcFound -= HandleNfc; | |
} | |
} | |
protected abstract void HandleNfc(object sender, NfcEventArgs e); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment