using UnityEngine; using System.Collections; using System; namespace SimpleFirebaseUnity { public class FirebaseObserver { public Action OnChange; protected FirebaseDatabase firebase; protected FirebaseDatabase target; protected float refreshRate; protected string getParam; protected bool active; protected bool firstTime; protected DataSnapshot lastSnapshot; protected IEnumerator routine; #region CONSTRUCTORS /// /// Creates an Observer that calls GetValue request at the given refresh rate (in seconds) and checks whether the value has changed. /// /// Firebase. /// Refresh rate (in seconds). /// Parameter value for the Get request that will be called periodically. public FirebaseObserver(FirebaseDatabase _firebase, float _refreshRate, string _getParam = "") { active = false; lastSnapshot = null; firebase = _firebase; refreshRate = _refreshRate; getParam = _getParam; target = _firebase.Copy (); routine = null; } /// /// Creates an Observer that calls GetValue request at the given refresh rate (in seconds) and checks whether the value has changed. /// /// Firebase. /// Refresh rate (in seconds). /// Parameter value for the Get request that will be called periodically. public FirebaseObserver(FirebaseDatabase _firebase, float _refreshRate, FirebaseParam _getParam) { active = false; lastSnapshot = null; firebase = _firebase; refreshRate = _refreshRate; getParam = _getParam.Parameter; target = _firebase.Copy (); } #endregion #region OBSERVER FUNCTIONS /// /// Start the observer. /// public void Start() { if (routine != null) Stop (); active = true; firstTime = true; target.OnGetSuccess += CompareSnapshot; routine = RefreshCoroutine (); target.root.StartCoroutine (routine); } /// /// Stop the observer. /// public void Stop() { active = false; target.OnGetSuccess -= CompareSnapshot; lastSnapshot = null; if (routine != null) { target.root.StopCoroutine (routine); routine = null; } } IEnumerator RefreshCoroutine() { while (active) { target.GetValue (); yield return new WaitForSeconds (refreshRate); } } void CompareSnapshot(FirebaseDatabase target, DataSnapshot snapshot) { if (firstTime) { firstTime = false; lastSnapshot = snapshot; return; } if (lastSnapshot != null) { if (!snapshot.RawJson.Equals (lastSnapshot.RawJson)) { if (OnChange != null) OnChange (firebase, snapshot); } } lastSnapshot = snapshot; } #endregion } }