tshm
6/16/2015 - 11:26 PM

Rx sample

Rx sample

        public void Start()
        {
            var player = new Alarm();
            //player.Play();
            LogManager.GetCurrentClassLogger().Info("starting to monitor.");

            var timedObserver = Observable.Interval(TimeSpan.FromSeconds(50));
            var netObserver = StatusObserverFactory.GetNetworkStatusObserver();
            var powObserver = StatusObserverFactory.GetPowerStatusObserver();

            timedObserver.CombineLatest(powObserver, netObserver, (i, pow, net) => !(pow || net))
                //.DistinctUntilChanged()
            .Subscribe(s => React(player, s),
                err => LogManager.GetCurrentClassLogger().Error("Error: {0}", err));
        }
    internal static class StatusObserverFactory
    {
        static public IObservable<bool> GetPowerStatusObserver()
        {
            var obs = Observable.FromEvent<PowerModeChangedEventHandler, PowerModeChangedEventArgs>(
                evc => (sender, evt) => evc(evt),
                h => SystemEvents.PowerModeChanged += h,
                h => SystemEvents.PowerModeChanged -= h
            ).Where(evt => evt.Mode == PowerModes.StatusChange)
            .Select(
              _ => SystemInformation.PowerStatus.PowerLineStatus == PowerLineStatus.Online
            )
            .StartWith(true);
            obs.Subscribe(e => LogManager.GetCurrentClassLogger().Trace("power : {0}", e));

            LogManager.GetCurrentClassLogger().Trace("Subscribe to power event");
            return obs;
        }

        static public IObservable<bool> GetNetworkStatusObserver()
        {
            var obs = Observable.FromEvent<NetworkAvailabilityChangedEventHandler, NetworkAvailabilityEventArgs>(
                evc => (sender, evt) => evc(evt),
                h => NetworkChange.NetworkAvailabilityChanged += h,
                h => NetworkChange.NetworkAvailabilityChanged -= h
            )
            .Select(evt => evt.IsAvailable)
            .StartWith(true);
            obs.Subscribe(e => LogManager.GetCurrentClassLogger().Trace("network : {0}", e));

            LogManager.GetCurrentClassLogger().Trace("Subscribe to network event");
            return obs;
        }
    }