コード例 #1
1
        public void Should_Produce_Correct_Values()
        {
            var activator = new BehaviorSubject<bool>(false);
            var source = new BehaviorSubject<object>(1);
            var target = new ActivatedObservable(activator, source, string.Empty);
            var result = new List<object>();

            target.Subscribe(x => result.Add(x));

            activator.OnNext(true);
            source.OnNext(2);
            activator.OnNext(false);
            source.OnNext(3);
            activator.OnNext(true);

            Assert.Equal(
                new[] 
                {
                    AvaloniaProperty.UnsetValue,
                    1,
                    2,
                    AvaloniaProperty.UnsetValue,
                    3,
                }, 
                result);
        }
コード例 #2
0
        public ExecutionContext(TimeSpan skipAhead = default(TimeSpan))
        {
            this.disposables = new CompositeDisposable();
            this.cancelRequested = new BehaviorSubject<bool>(false)
                .AddTo(this.disposables);
            this.progressDeltas = new Subject<TimeSpan>()
                .AddTo(this.disposables);

            this
                .cancelRequested
                .Where(x => x)
                .Subscribe(_ => this.IsCancelled = true)
                .AddTo(this.disposables);

            this
                .progressDeltas
                .Scan((running, next) => running + next)
                .Subscribe(x => this.Progress = x)
                .AddTo(this.disposables);

            this
                .WhenAnyValue(x => x.CurrentExercise)
                .Select(x => this.progressDeltas.StartWith(TimeSpan.Zero).Scan((running, next) => running + next))
                .Switch()
                .Subscribe(x => this.CurrentExerciseProgress = x)
                .AddTo(this.disposables);

            this
                .progressDeltas
                .StartWith(skipAhead)
                .Scan((running, next) => running - next)
                .Select(x => x < TimeSpan.Zero ? TimeSpan.Zero : x)
                .Subscribe(x => this.SkipAhead = x)
                .AddTo(this.disposables);
        }
コード例 #3
0
ファイル: MainMenu.cs プロジェクト: HaKDMoDz/shooter
        public MainMenu(Engine engine)
            : base(engine)
        {
            this.button1 = new MenuButton(this.Engine);
            this.button2 = new MenuButton(this.Engine);

            this.button1.Position = new Vector2(0, -40);
            this.button2.Position = new Vector2(0, 40);

            this.button1.Text = "new game";
            this.button2.Text = "high scores";

            this.button1.Color = new Color(0.3f, 0.3f, 0.3f);
            this.button2.Color = new Color(0.3f, 0.3f, 0.3f);

            button1.Action = () =>
                                 {
                                     this.Dispose();
                                     new NewGameMenu(this.Engine).Initialize().Attach();
                                 };

            button2.Action = () =>
                                 {
                                     this.Dispose();
                                     new HighScoreMenu(this.Engine).Initialize().Attach();
                                 };

            this.buttons.Add(button1);
            this.buttons.Add(button2);

            this.oldButton = new BehaviorSubject<MenuButton>(null);
            this.currentButton = new BehaviorSubject<MenuButton>(this.button1);
        }
コード例 #4
0
ファイル: SharedThemeService.cs プロジェクト: a-wall/radar
 public SharedThemeService(ResourceDictionary resourceDictionary)
 {
     _resourceDictionary = resourceDictionary;
     _themes = new BehaviorSubject<IEnumerable<ITheme>>(Enumerable.Empty<ITheme>());
     _activeTheme = new BehaviorSubject<ITheme>(null);
     _themesMap = new Dictionary<string, ITheme>();
 }
コード例 #5
0
ファイル: AudioPlayer.cs プロジェクト: hur1can3/Espera
        internal AudioPlayer()
        {
            this.audioPlayerCallback = new DummyMediaPlayerCallback();
            this.videoPlayerCallback = new DummyMediaPlayerCallback();
            this.currentCallback = new DummyMediaPlayerCallback();

            this.finishSubscription = new SerialDisposable();
            this.gate = new SemaphoreSlim(1, 1);

            this.playbackState = new BehaviorSubject<AudioPlayerState>(AudioPlayerState.None);
            this.PlaybackState = this.playbackState.DistinctUntilChanged();

            this.loadedSong = new BehaviorSubject<Song>(null);
            this.TotalTime = this.loadedSong.Select(x => x == null ? TimeSpan.Zero : x.Duration);

            this.currentTimeChangedFromOuter = new Subject<TimeSpan>();

            var conn = Observable.Interval(TimeSpan.FromMilliseconds(300), RxApp.TaskpoolScheduler)
                .CombineLatest(this.PlaybackState, (l, state) => state)
                .Where(x => x == AudioPlayerState.Playing)
                .Select(_ => this.CurrentTime)
                .Merge(this.currentTimeChangedFromOuter)
                .DistinctUntilChanged(x => x.TotalSeconds)
                .Publish(TimeSpan.Zero);
            conn.Connect();
            this.CurrentTimeChanged = conn;
        }
コード例 #6
0
ファイル: BindingTests.cs プロジェクト: furesoft/Perspex
        public void OneTime_Binding_Should_Be_Set_Up()
        {
            var dataContext = new BehaviorSubject<object>(null);
            var expression = new BehaviorSubject<object>(null);
            var target = CreateTarget(dataContext: dataContext);
            var binding = new Binding
            {
                Path = "Foo",
                Mode = BindingMode.OneTime,
            };

            binding.Bind(target.Object, TextBox.TextProperty, expression);

            target.Verify(x => x.SetValue(
                (PerspexProperty)TextBox.TextProperty, 
                null, 
                BindingPriority.LocalValue));
            target.ResetCalls();

            expression.OnNext("foo");
            dataContext.OnNext(1);

            target.Verify(x => x.SetValue(
                (PerspexProperty)TextBox.TextProperty,
                "foo",
                BindingPriority.LocalValue));
        }
コード例 #7
0
        public void live_values_are_sent_through_scheduler()
        {
            ManualScheduler scheduler = new ManualScheduler();

            BehaviorSubject<int> subject = new BehaviorSubject<int>(0, scheduler);

            StatsObserver<int> stats = new StatsObserver<int>();

            subject.Subscribe(stats);

            subject.OnNext(1);
            subject.OnNext(2);
            subject.OnCompleted();

            Assert.IsFalse(stats.NextCalled);

            scheduler.RunNext();
            Assert.AreEqual(1, stats.NextCount);
            Assert.IsTrue(stats.NextValues.SequenceEqual(new int[] { 0 }));
            Assert.IsFalse(stats.CompletedCalled);

            scheduler.RunNext();
            Assert.AreEqual(2, stats.NextCount);
            Assert.IsTrue(stats.NextValues.SequenceEqual(new int[] { 0, 1 }));
            Assert.IsFalse(stats.CompletedCalled);

            scheduler.RunNext();
            Assert.AreEqual(3, stats.NextCount);
            Assert.IsTrue(stats.NextValues.SequenceEqual(new int[] { 0, 1, 2 }));
            Assert.IsFalse(stats.CompletedCalled);

            scheduler.RunNext();
            Assert.IsTrue(stats.CompletedCalled);
        }
コード例 #8
0
        public AnalyticsEngine()
        {
            _currentPositionUpdatesDto = new PositionUpdatesDto();
            _updates = new BehaviorSubject<PositionUpdatesDto>(_currentPositionUpdatesDto);

            _eventLoopScheduler.SchedulePeriodic(TimeSpan.FromSeconds(10), PublishPositionReport);
        }
コード例 #9
0
        public MainWindowViewModel()
        {
            var noneInFlight = new BehaviorSubject<bool>(false);
            var updateManager = default(UpdateManager);

            this.WhenAny(x => x.UpdatePath, x => x.Value)
                .Where(x => !String.IsNullOrWhiteSpace(x))
                .Throttle(TimeSpan.FromMilliseconds(700), RxApp.DeferredScheduler)
                .Subscribe(x => {
                    if (updateManager != null)  updateManager.Dispose();
                    updateManager = new UpdateManager(UpdatePath, "SampleUpdatingApp", FrameworkVersion.Net40);
                });

            CheckForUpdate = new ReactiveAsyncCommand(noneInFlight);
            CheckForUpdate.RegisterAsyncObservable(_ => updateManager.CheckForUpdate())
                .Subscribe(x => { UpdateInfo = x; DownloadedUpdateInfo = null; });

            DownloadReleases = new ReactiveAsyncCommand(noneInFlight.Where(_ => UpdateInfo != null));
            DownloadReleases.RegisterAsyncObservable(_ => updateManager.DownloadReleases(UpdateInfo.ReleasesToApply))
                .Subscribe(_ => DownloadedUpdateInfo = UpdateInfo);

            ApplyReleases = new ReactiveAsyncCommand(noneInFlight.Where(_ => DownloadedUpdateInfo != null));
            ApplyReleases.RegisterAsyncObservable(_ => updateManager.ApplyReleases(DownloadedUpdateInfo));

            Observable.CombineLatest(
                CheckForUpdate.ItemsInflight.StartWith(0),
                DownloadReleases.ItemsInflight.StartWith(0),
                ApplyReleases.ItemsInflight.StartWith(0),
                this.WhenAny(x => x.UpdatePath, _ => 0),
                (a, b, c, _) => a + b + c
            ).Select(x => x == 0 && UpdatePath != null).Multicast(noneInFlight).Connect();
        }
コード例 #10
0
 protected OnOffFeature(bool @on)
 {
     availability = new BehaviorSubject<bool>(@on);
     activator = new FeatureActivator(
         Activate,
         Deactivate,
         availability);
 }
コード例 #11
0
 public static void BehaviorSubjectExample3()
 {
     var subject = new BehaviorSubject<string>("a");
     subject.OnNext("b");
     subject.Subscribe(Console.WriteLine);
     subject.OnNext("c");
     subject.OnNext("d");
 }
コード例 #12
0
ファイル: StyleBindingTests.cs プロジェクト: Arlorean/Perspex
        public async void Should_Produce_UnsetValue_On_Activator_False()
        {
            var activator = new BehaviorSubject<bool>(false);
            var target = new StyleBinding(activator, 1, string.Empty);
            var result = await target.Take(1);

            Assert.Equal(PerspexProperty.UnsetValue, result);
        }
コード例 #13
0
ファイル: StyleBindingTests.cs プロジェクト: Arlorean/Perspex
        public async void Should_Produce_Value_On_Activator_True()
        {
            var activator = new BehaviorSubject<bool>(true);
            var target = new StyleBinding(activator, 1, string.Empty);
            var result = await target.Take(1);

            Assert.Equal(1, result);
        }
コード例 #14
0
        public iCloudExerciseDocumentService(ILoggerService loggerService)
        {
            Ensure.ArgumentNotNull(loggerService, nameof(loggerService));

            this.logger = loggerService.GetLogger(this.GetType());
            this.exerciseDocument = new BehaviorSubject<string>(null);
            this.sync = new object();
        }
コード例 #15
0
ファイル: TestBehaviorSubject.cs プロジェクト: pudae/lplpl
 static void Example4()
 {
     var subject = new BehaviorSubject<string>("a");
       subject.OnNext("b");
       subject.OnNext("c");
       subject.OnNext("d");
       subject.OnCompleted();
       subject.Subscribe(Console.WriteLine);
 }
コード例 #16
0
        public ServiceControl(IBlobCache cache, string url = null)
        {
            this.cache = cache;
            subject = new BehaviorSubject<Unit>(Unit.Default);
            isValid = new BehaviorSubject<bool>(false);
            IsValid = isValid.AsObservable();

            UpdateUrl(url ?? "http://localhost:33333/api").Wait();
        }
コード例 #17
0
ファイル: WebSocketLab.cs プロジェクト: ibebbs/Rxx
    protected override void Main()
    {
      if (Environment.OSVersion.Version < new Version(6, 2))
      {
        TraceError(Text.LabRequiresWindows8OrHigher);
        return;
      }

      const int port = 5494;
      string subProtocol = GetType().Name;

      var userMessages = new BehaviorSubject<string>(null);

      var client = new ClientWebSocket();

      client.Options.AddSubProtocol(subProtocol);

      using (client)
      using (var cancel = new CancellationDisposable())
      using (ObservableHttpListener
        .StartWebSockets(new IPEndPoint(IPAddress.Loopback, port), subProtocol)
        .Subscribe(
          async request =>
          {
            using (var socket = request.WebSocket)
            {
              try
              {
                var message = await ReceiveMessageAsync(socket, cancel.Token);
                await SendMessageAsync("You sent \"" + message + "\"", socket, cancel.Token);
                await ReceiveCloseMessageAsync(socket, cancel.Token);
              }
              catch (OperationCanceledException)
              {
              }
            }
          },
          TraceError))
      using ((from _ in client.ConnectAsync(new Uri("ws://localhost:" + port), cancel.Token).ToObservable()
                .Do(_ => TraceLine(Environment.NewLine + "(Connected to host on sub-protocol \"{0}\")", client.SubProtocol))
              from message in userMessages.Where(m => m != null).Take(1)
              from __ in SendMessageAsync(message, client, cancel.Token).ToObservable()
              from response in ReceiveMessageAsync(client, cancel.Token).ToObservable()
                .Do(___ => client.CloseAsync(WebSocketCloseStatus.NormalClosure, "Done", cancel.Token))
              select response)
              .Subscribe(
                response => TraceLine("Response: {0}", response),
                TraceError,
                () => TraceLine("{0}: {1}", Text.Client, Text.Done)))
      {
        userMessages.OnNext(UserInput("{0}> ", Instructions.EnterAMessage));

        TraceStatus(Instructions.PressAnyKeyToCancel);

        WaitForKey();
      }
    }
コード例 #18
0
ファイル: RedisLogger.cs プロジェクト: g-un--/log4net.redis
        internal RedisLogger(string key, ILog log, IRedisConnectionFactory redisConnectionFactory)
        {
            this.key = string.Format(CultureInfo.InvariantCulture, "{0}:{1}", log.Logger.Name, key);
            this.log = log;
            this.messagesSubject = new ReplaySubject<Tuple<string, string>>(100, TimeSpan.FromSeconds(5));
            this.retry = new BehaviorSubject<bool>(false);

            var redisOnConnectionAction = new Action<Task<RedisConnection>>(task =>
            {
                if (task.IsCompleted && !task.IsFaulted)
                {
                    Interlocked.CompareExchange<RedisConnection>(ref this.redisConnection, task.Result, null);
                    subscription = messagesSubject.TakeUntil(retry.Skip(1)).Subscribe((item) => 
                        {
                            redisConnection.Publish(item.Item1, item.Item2).ContinueWith(taskWithException =>
                                {
                                    taskWithException.Exception.Handle(ex => true);
                                }, TaskContinuationOptions.OnlyOnFaulted);
                        });
                }
            });

            var redisOnErrorAction = new Action<ErrorEventArgs>(ex =>
                {
                    if (ex.IsFatal)
                    {
                        retry.OnNext(true);
                        Interlocked.Exchange<RedisConnection>(ref this.redisConnection, null);
                    }
                });

            Action subscribeAction = () =>
            {
                var connectionTask = redisConnectionFactory.CreateRedisConnection();
                connectionTask.ContinueWith(taskConnection =>
                    {
                        if (!taskConnection.IsFaulted)
                        {
                            taskConnection.ContinueWith(redisOnConnectionAction);
                            taskConnection.Result.Error += (_, err) => redisOnErrorAction(err);
                        }
                        else
                        {
                            taskConnection.Exception.Handle(_ => true);
                            this.retry.OnNext(true);
                        }
                    });
            };

            retry.Subscribe(val =>
                {
                    if (val)
                        Observable.Timer(TimeSpan.FromSeconds(10)).Subscribe(_ => subscribeAction()); 
                    else
                        subscribeAction();
                });
        }
コード例 #19
0
ファイル: LocalSong.cs プロジェクト: hur1can3/Espera
        /// <summary>
        /// Initializes a new instance of the <see cref="LocalSong" /> class.
        /// </summary>
        /// <param name="path">The path of the file.</param>
        /// <param name="duration">The duration of the song.</param>
        /// <param name="artworkKey">
        /// The key of the artwork for Akavache to retrieve. Null, if there is no album cover or the
        /// artwork isn't retrieved yet.
        /// </param>
        public LocalSong(string path, TimeSpan duration, string artworkKey = null)
            : base(path, duration)
        {
            if (artworkKey == String.Empty)
                Throw.ArgumentException("Artwork key cannot be an empty string", () => artworkKey);

            this.artworkKey = new BehaviorSubject<string>(artworkKey);

            this.Guid = Guid.NewGuid();
        }
コード例 #20
0
        public void Should_Complete_When_Activator_Completes()
        {
            var activator = new BehaviorSubject<bool>(false);
            var target = new ActivatedValue(activator, 1, string.Empty);
            var completed = false;

            target.Subscribe(_ => { }, () => completed = true);
            activator.OnCompleted();

            Assert.True(completed);
        }
コード例 #21
0
        public void Should_Complete_When_Source_Observable_Errors()
        {
            var source = new BehaviorSubject<object>(1);
            var target = new ExpressionObserver(source, "Foo");
            var completed = false;

            target.Subscribe(_ => { }, () => completed = true);
            source.OnError(new Exception());

            Assert.True(completed);
        }
コード例 #22
0
 ///<summary>
 ///With BehaviourSubject<T> ,the subscriber will only get all the last publication made
 ///Simply, BehaviourSubject has a one value buffer. Hence, it requires a default value.
 ///</summary>
 private static void BehaviourSubject()
 {
     var subject = new BehaviorSubject<string>("Rx");
         subject.OnNext("a");
         var d = subject.Subscribe(x => Console.WriteLine("Subscritipon 1 : " + x));
         subject.OnNext("b");
        // var d = subject.Subscribe(x => Console.WriteLine("Subscritipon 1 : " + x));
         d.Dispose();
         subject.OnNext("c");
         subject.Subscribe(x => Console.WriteLine("Subscritipon 2 : " + x));
 }
コード例 #23
0
        /// <summary>
        /// Subscribe for all content against a given row key
        /// </summary>
        /// <param name="rowKey">Row key to index on</param>
        /// <returns>Observable value representing the subscription</returns>
        public IObservable<IConstituentRow> Subscribe(object rowKey)
        {
            IObservable<IConstituentRow> subject;
            if (!singleTableSubjects.TryGetValue(rowKey, out subject))
            {
                subject = new BehaviorSubject<IConstituentRow>(null);
                singleTableSubjects.Add(rowKey, subject);
            }

            return subject;
        }
コード例 #24
0
        public void Should_Complete_When_Source_Completes()
        {
            var activator = new BehaviorSubject<bool>(false);
            var source = new BehaviorSubject<object>(1);
            var target = new ActivatedObservable(activator, source, string.Empty);
            var completed = false;

            target.Subscribe(_ => { }, () => completed = true);
            source.OnCompleted();

            Assert.True(completed);
        }
コード例 #25
0
ファイル: SetterTests.cs プロジェクト: KvanTTT/Perspex
        public void Setter_Should_Apply_Binding_To_Property()
        {
            var control = new TextBlock();
            var subject = new BehaviorSubject<object>("foo");
            var binding = Mock.Of<IBinding>(x => x.CreateSubject(control, TextBlock.TextProperty) == subject);
            var style = Mock.Of<IStyle>();
            var setter = new Setter(TextBlock.TextProperty, binding);

            setter.Apply(style, control, null);

            Assert.Equal("foo", control.Text);
        }
コード例 #26
0
        public GoogleDriveExerciseDocumentService(
            ILoggerService loggerService,
            IConnectionResultHandler connectionResultHandler)
        {
            Ensure.ArgumentNotNull(loggerService, nameof(loggerService));
            Ensure.ArgumentNotNull(connectionResultHandler, nameof(connectionResultHandler));

            this.logger = loggerService.GetLogger(this.GetType());
            this.connectionResultHandler = connectionResultHandler;
            this.exerciseDocument = new BehaviorSubject<string>(null);
            this.sync = new object();
            this.connectedDisposable = new SerialDisposable();
        }
コード例 #27
0
ファイル: SetterTests.cs プロジェクト: jkoritzinsky/Avalonia
        public void Setter_Should_Apply_Binding_To_Property()
        {
            var control = new TextBlock();
            var subject = new BehaviorSubject<object>("foo");
            var descriptor = new InstancedBinding(subject);
            var binding = Mock.Of<IBinding>(x => x.Initiate(control, TextBlock.TextProperty, null, false) == descriptor);
            var style = Mock.Of<IStyle>();
            var setter = new Setter(TextBlock.TextProperty, binding);

            setter.Apply(style, control, null);

            Assert.Equal("foo", control.Text);
        }
コード例 #28
0
ファイル: StyleBindingTests.cs プロジェクト: Arlorean/Perspex
        public void Should_Change_Value_On_Activator_Change()
        {
            var activator = new BehaviorSubject<bool>(false);
            var target = new StyleBinding(activator, 1, string.Empty);
            var result = new List<object>();

            target.Subscribe(x => result.Add(x));

            activator.OnNext(true);
            activator.OnNext(false);

            Assert.Equal(new[] { PerspexProperty.UnsetValue, 1, PerspexProperty.UnsetValue }, result);
        }
コード例 #29
0
        public void Should_Produce_Correct_Values()
        {
            var activator = new BehaviorSubject<bool>(false);
            var target = new ActivatedValue(activator, 1, string.Empty);
            var result = new List<object>();

            target.Subscribe(x => result.Add(x));

            activator.OnNext(true);
            activator.OnNext(false);

            Assert.Equal(new[] { PerspexProperty.UnsetValue, 1, PerspexProperty.UnsetValue }, result);
        }
コード例 #30
0
    public void StickyItemShouldBeAddedWhenSelectionChangesFromNull()
    {
        var source = CreateSource();
        var selection = new BehaviorSubject<Thing>(null);
        var stickie = new Thing();
        var target = source.CreateListenerCollection(stickie, selection);

        CollectionAssert.AreEqual(source, target);

        selection.OnNext(source[0]);

        var expected = new[] { stickie }.Concat(source);
        CollectionAssert.AreEqual(expected, target);
    }
コード例 #31
0
ファイル: Animation.cs プロジェクト: sverrewl/dmd-extensions
        /// <summary>
        /// Tuät d Animazion looslah und d Biudli uifd viärbit-Queuä uisgäh
        /// </summary>
        /// <remarks>
        /// Das hiä isch dr Fau wo Buider vo VPM mit zwe Bits erwiiterid wärdid.
        ///
        /// S Timing wird wiä im Modus eis vo dr Animazion vorgäh, das heisst s
        /// letschtä Biud vo VPM definiärt diä erschtä zwäi Bits unds jedes Biud
        /// vord Animazion tuät diä reschtlichä zwäi Bits ergänzä unds de uifd
        /// Viärbit-Queuä uisgäh.
        /// </remarks>
        /// <param name="firstFrame">S Buid vo VPM wod Animazion losgla het</param>
        /// <param name="coloredGray4Source">D Uisgab vord erwiitertä Frames</param>
        /// <param name="palette">D Palettä wo zum iifärbä bruicht wird</param>
        /// <param name="completed">Wird uisgfiärt wenn fertig</param>
        public void StartEnhance(byte[][] firstFrame, Subject <Tuple <byte[][], Color[]> > coloredGray4Source, BehaviorSubject <Palette> palette, Action completed = null)
        {
            Logger.Info("[fsq] Starting enhanced animation of {0} frames...", _frames.Length);
            IsRunning = true;
            var t = DateTime.Now.Ticks / TimeSpan.TicksPerMillisecond;
            var n = 0;

            _vpmFrames = new BehaviorSubject <byte[][]>(firstFrame);
            _animation = _fsqFrames
                         .Select(fsqFrame => new [] { _vpmFrames.Value[0], _vpmFrames.Value[1], fsqFrame.Planes[0], fsqFrame.Planes[1] })
                         .Subscribe(planes => {
                //Logger.Trace("[timing] FSQ enhanced Frame #{0} played ({1} ms, theory: {2} ms).", n, (DateTime.Now.Ticks / TimeSpan.TicksPerMillisecond) - t, _frames[n].Time);
                coloredGray4Source.OnNext(new Tuple <byte[][], Color[]>(planes, palette.Value.GetColors(planes.Length)));
                n++;
            }, () => {
                //Logger.Trace("[timing] Last frame enhanced, waiting {0}ms for last frame to finish playing.", _frames[_frames.Length - 1].Delay);

                // nu uifs letschti biud wartä bis mer fertig sind
                Observable
                .Never <Unit>()
                .StartWith(Unit.Default)
                .Delay(TimeSpan.FromMilliseconds(_frames[_frames.Length - 1].Delay))
                .Subscribe(_ => {
                    IsRunning = false;
                    completed?.Invoke();
                });
            });
        }
コード例 #32
0
ファイル: Animation.cs プロジェクト: sverrewl/dmd-extensions
        /// <summary>
        /// Tuät d Animazion looslah und d Biudli uif diä entschprächendi Queuä
        /// uisgäh.
        /// </summary>
        /// <remarks>
        /// Das hiä isch dr Fau wo diä gsamti Animazion uisgäh und VPM ignoriärt
        /// wird (dr Modus eis).
        /// </remarks>
        /// <param name="coloredGray2Source">Wenn meglich gahts da druif</param>
        /// <param name="coloredGray4Source">Wenns viärbittig isch, de wird dä zersch probiärt</param>
        /// <param name="palette">D Palettä wo zum iifärbä bruicht wird</param>
        /// <param name="completed">Wird uisgfiärt wenn fertig</param>
        public void StartReplace(Subject <Tuple <byte[][], Color[]> > coloredGray2Source, Subject <Tuple <byte[][], Color[]> > coloredGray4Source, BehaviorSubject <Palette> palette, Action completed = null)
        {
            Logger.Info("[fsq] Starting colored gray4 animation of {0} frames...", _frames.Length);
            IsRunning = true;
            var t = DateTime.Now.Ticks / TimeSpan.TicksPerMillisecond;
            var n = 0;

            _animation = _fsqFrames
                         .Subscribe(frame => {
                //Logger.Trace("[timing] FSQ Frame #{0} played ({1} ms, theory: {2} ms).", n, (DateTime.Now.Ticks / TimeSpan.TicksPerMillisecond) - t, _frames[n].Time);
                if (frame.BitLength == 2)
                {
                    coloredGray2Source.OnNext(new Tuple <byte[][], Color[]>(frame.Planes, palette.Value.GetColors(frame.BitLength)));
                }
                else
                {
                    coloredGray4Source.OnNext(new Tuple <byte[][], Color[]>(frame.Planes, palette.Value.GetColors(frame.BitLength)));
                }
                n++;
            }, () => {
                // nu uifs letschti biud wartä bis mer fertig sind
                Observable
                .Never <Unit>()
                .StartWith(Unit.Default)
                .Delay(TimeSpan.FromMilliseconds(_frames[_frames.Length - 1].Delay))
                .Subscribe(_ => {
                    IsRunning = false;
                    completed?.Invoke();
                });
            });
        }
コード例 #33
0
 public InMemoryEventStore()
 {
     flowEvents = new ConcurrentDictionary <FlowContext, ReplaySubject <FlowEvent> >();
     allFlowEventsObservable = new BehaviorSubject <FlowEvent>(null);
 }
コード例 #34
0
        /// <summary>
        /// 使用 Subject
        /// Subject代表了IObservable和IObserver这两个接口的实现
        /// </summary>
        /// <param name="args"></param>
        static void Main(string[] args)
        {
            // 一旦订阅了Subject,它就会把事件序列发送给订阅者
            Console.WriteLine("Subject");
            var subject = new Subject <string>();

            subject.OnNext("A"); // A在订阅之前,不会被打印
            using (var subscription = OutputToConsole(subject))
            {
                subject.OnNext("B");
                subject.OnNext("C");
                subject.OnNext("D");
                // 当调用OnCompleted或OnError方法时,事件序列传播会被停止
                subject.OnCompleted();
                // 事件传播停止之后的事件不会被打印
                subject.OnNext("Will not be printed out");
            }

            Console.WriteLine("ReplaySubject");
            // ReplaySubject可以缓存从广播开始的所有事件
            var replaySubject = new ReplaySubject <string>();

            replaySubject.OnNext("A");
            // 稍后订阅也可以获得之前的事件
            using (var subscription = OutputToConsole(replaySubject))
            {
                replaySubject.OnNext("B");
                replaySubject.OnNext("C");
                replaySubject.OnNext("D");
                replaySubject.OnCompleted();
            }
            Console.WriteLine("Buffered ReplaySubject");
            // 指定ReplaySubject缓存的大小
            // 参数2表示只可以缓存最后的2个事件
            var bufferedSubject = new ReplaySubject <string>(2);

            bufferedSubject.OnNext("A");
            bufferedSubject.OnNext("B");
            bufferedSubject.OnNext("C");
            using (var subscription = OutputToConsole(bufferedSubject))
            {
                bufferedSubject.OnNext("D");
                bufferedSubject.OnCompleted();
            }

            Console.WriteLine("Time window ReplaySubject");
            // 指定ReplaySubject缓存的事件
            // TimeSpan.FromMilliseconds(200) 表示只缓存200ms内发生的事件
            var timeSubject = new ReplaySubject <string>(TimeSpan.FromMilliseconds(200));

            timeSubject.OnNext("A");
            Thread.Sleep(TimeSpan.FromMilliseconds(100));
            timeSubject.OnNext("B");
            Thread.Sleep(TimeSpan.FromMilliseconds(100));
            timeSubject.OnNext("C");
            Thread.Sleep(TimeSpan.FromMilliseconds(100));
            using (var subscription = OutputToConsole(timeSubject))
            {
                Thread.Sleep(TimeSpan.FromMilliseconds(300));
                timeSubject.OnNext("D");
                timeSubject.OnCompleted();
            }

            Console.WriteLine("AsyncSubject");
            // AsyncSubject类似于任务并行库中的Task类型
            // 它代表了单个异步操作
            // 如果有多个事件发布,它将等待事件序列完成,并把最后一个事件提供给订阅者
            var asyncSubject = new AsyncSubject <string>();

            asyncSubject.OnNext("A");
            using (var subscription = OutputToConsole(asyncSubject))
            {
                asyncSubject.OnNext("B");
                asyncSubject.OnNext("C");
                asyncSubject.OnNext("D");
                asyncSubject.OnCompleted();
            }

            Console.WriteLine("BehaviorSubject");
            // BehaviorSubject与ReplaySubject很相似,但它只缓存一个值
            // 并允许万一还没有发送任何通知时,指定一个默认值
            // 默认值会被自动替换为订阅前的最后一个事件
            var behaviorSubject = new BehaviorSubject <string>("Default");

            using (var subscription = OutputToConsole(behaviorSubject))
            {
                behaviorSubject.OnNext("B");
                behaviorSubject.OnNext("C");
                behaviorSubject.OnNext("D");
                behaviorSubject.OnCompleted();
            }

            Console.ReadLine();
        }
コード例 #35
0
        public void BehaviorSubject()
        {
            // OnCompletedPattern
            {
                var subject = new BehaviorSubject <int>(3333);

                var onNext               = new List <int>();
                var exception            = new List <Exception>();
                int onCompletedCallCount = 0;
                var _ = subject.Subscribe(x => onNext.Add(x), x => exception.Add(x), () => onCompletedCallCount++);

                onNext.Is(3333);

                subject.OnNext(1);
                subject.OnNext(10);
                subject.OnNext(100);
                subject.OnNext(1000);

                onNext.Is(3333, 1, 10, 100, 1000);

                // re subscription
                onNext.Clear();
                _.Dispose();
                subject.Subscribe(x => onNext.Add(x), x => exception.Add(x), () => onCompletedCallCount++);
                onNext.Is(1000);

                subject.OnCompleted();
                onCompletedCallCount.Is(1);

                subject.OnNext(1);
                subject.OnNext(10);
                subject.OnNext(100);
                onNext.Count.Is(1);

                subject.OnCompleted();
                subject.OnError(new Exception());
                exception.Count.Is(0);
                onCompletedCallCount.Is(1);

                // ++subscription
                onNext.Clear();
                onCompletedCallCount = 0;
                subject.Subscribe(x => onNext.Add(x), x => exception.Add(x), () => onCompletedCallCount++);
                onNext.Count.Is(0);
                exception.Count.Is(0);
                onCompletedCallCount.Is(1);
            }

            // OnErrorPattern
            {
                var subject = new BehaviorSubject <int>(3333);

                var onNext               = new List <int>();
                var exception            = new List <Exception>();
                int onCompletedCallCount = 0;
                subject.Subscribe(x => onNext.Add(x), x => exception.Add(x), () => onCompletedCallCount++);

                subject.OnNext(1);
                subject.OnNext(10);
                subject.OnNext(100);
                subject.OnNext(1000);
                onNext.Is(3333, 1, 10, 100, 1000);

                subject.OnError(new Exception());
                exception.Count.Is(1);

                subject.OnNext(1);
                subject.OnNext(10);
                subject.OnNext(100);
                onNext.Count.Is(5);

                subject.OnCompleted();
                subject.OnError(new Exception());
                exception.Count.Is(1);
                onCompletedCallCount.Is(0);

                // ++subscription
                onNext.Clear();
                exception.Clear();
                onCompletedCallCount = 0;
                subject.Subscribe(x => onNext.Add(x), x => exception.Add(x), () => onCompletedCallCount++);
                onNext.Count.Is(0);
                exception.Count.Is(1);
                onCompletedCallCount.Is(0);
            }
        }
コード例 #36
0
        public void Should_pause_and_resume()
        {
            //Arrange
            var    scheduler        = new TestScheduler();
            var    isRunningTrigger = new BehaviorSubject <bool>(true);
            Action pause            = () => isRunningTrigger.OnNext(false);
            Action resume           = () => isRunningTrigger.OnNext(true);
            var    source           = scheduler.CreateHotObservable(
                ReactiveTest.OnNext(0.1.Seconds(), 1),
                ReactiveTest.OnNext(2.0.Seconds(), 2),
                ReactiveTest.OnNext(4.0.Seconds(), 3),
                ReactiveTest.OnNext(6.0.Seconds(), 4),
                ReactiveTest.OnNext(8.0.Seconds(), 5));

            scheduler.Schedule(TimeSpan.FromSeconds(0.5), () => { pause(); });
            scheduler.Schedule(TimeSpan.FromSeconds(5.0), () => { resume(); });

            //Act
            var sut = Observable.Create <IObservable <int> >(o =>
            {
                var current           = source.Replay();
                var connection        = new SerialDisposable();
                connection.Disposable = current.Connect();
                return(isRunningTrigger
                       .DistinctUntilChanged()
                       .Select(isRunning =>
                {
                    if (isRunning)
                    {
                        //Return the current replayed values.
                        return current;
                    }
                    else
                    {
                        //Disconnect and replace current.
                        current = source.Replay();
                        connection.Disposable = current.Connect();
                        //yield silence until the next time we resume.
                        return Observable.Never <int>();
                    }
                })
                       .Subscribe(o));
            }).Switch();
            var observer = scheduler.CreateObserver <int>();

            using (sut.Subscribe(observer))
            {
                scheduler.Start();
            }
            //Assert
            var expected = new[]
            {
                ReactiveTest.OnNext(0.1.Seconds(), 1),
                ReactiveTest.OnNext(5.0.Seconds(), 2),
                ReactiveTest.OnNext(5.0.Seconds(), 3),
                ReactiveTest.OnNext(6.0.Seconds(), 4),
                ReactiveTest.OnNext(8.0.Seconds(), 5)
            };

            CollectionAssert.AreEqual(expected, observer.Messages);
        }
コード例 #37
0
 public TaskInfoWrapper(JobInfo jobInfo, IOculiCredentialHelper credentialHelper)
 {
     this._jobInfo           = jobInfo;
     this._credentialHelper  = credentialHelper;
     this._persistenceStream = new BehaviorSubject <JobInfo>(jobInfo);
 }
コード例 #38
0
        public void MainTest()
        {
            WriteLine("Subject");
            var subject = new Subject <string>();

            subject.OnNext("A");
            using (var subscription = OutputToConsole(subject))
            {
                subject.OnNext("B");
                subject.OnNext("C");
                subject.OnNext("D");
                subject.OnCompleted();
                subject.OnNext("Will not be printed out");
            }
            WriteLine("ReplaySubject");
            var replaySubject = new ReplaySubject <string>();

            replaySubject.OnNext("A");
            using (var subscription = OutputToConsole(replaySubject))
            {
                replaySubject.OnNext("B");
                replaySubject.OnNext("C");
                replaySubject.OnNext("D");
                replaySubject.OnCompleted();
            }
            WriteLine("Buffered ReplaySubject");
            var bufferedSubject = new ReplaySubject <string>(2);

            bufferedSubject.OnNext("A");
            bufferedSubject.OnNext("b");
            bufferedSubject.OnNext("c");
            using (var subscription = OutputToConsole(bufferedSubject))
            {
                bufferedSubject.OnNext("D");
                bufferedSubject.OnCompleted();
            }
            WriteLine("Time window ReplaySubject");
            var timeSubject = new ReplaySubject <string>(TimeSpan.FromMilliseconds(200));

            timeSubject.OnNext("A");
            Thread.Sleep(TimeSpan.FromMilliseconds(100));
            timeSubject.OnNext("B");
            Thread.Sleep(TimeSpan.FromMilliseconds(100));
            timeSubject.OnNext("c");
            Thread.Sleep(TimeSpan.FromMilliseconds(100));
            using (var subscription = OutputToConsole(timeSubject))
            {
                Thread.Sleep(TimeSpan.FromMilliseconds(300));
                timeSubject.OnNext("D");
                timeSubject.OnCompleted();
            }
            WriteLine("AsyncSubject");
            var asyncSubject = new AsyncSubject <string>();

            asyncSubject.OnNext("A");
            using (var subscription = OutputToConsole(asyncSubject))
            {
                asyncSubject.OnNext("B");
                asyncSubject.OnNext("C");
                asyncSubject.OnNext("D");
                asyncSubject.OnCompleted();
            }
            WriteLine("BehaviorSubject");
            var behaviorSubject = new BehaviorSubject <string>("Default");

            using (var subscription = OutputToConsole(behaviorSubject))
            {
                behaviorSubject.OnNext("B");
                behaviorSubject.OnNext("C");
                behaviorSubject.OnNext("D");
                behaviorSubject.OnCompleted();
            }
        }
コード例 #39
0
 public static IBehaviorSubject <T> AsBehavior <T>(this BehaviorSubject <T> subject)
 {
     return(new BehaviorSubjectWrapper <T>(subject));
 }
コード例 #40
0
 internal UICollectionViewAdapter(UICollectionView view)
 {
     this.view            = view;
     this.isReloadingData = new BehaviorSubject <bool>(false);
 }
コード例 #41
0
        public void Finite()
        {
            var scheduler = new TestScheduler();

            var xs = scheduler.CreateHotObservable(
                OnNext(70, 1),
                OnNext(110, 2),
                OnNext(220, 3),
                OnNext(270, 4),
                OnNext(340, 5),
                OnNext(410, 6),
                OnNext(520, 7),
                OnCompleted <int>(630),
                OnNext(640, 9),
                OnCompleted <int>(650),
                OnError <int>(660, new Exception())
                );

            var subject      = default(BehaviorSubject <int>);
            var subscription = default(IDisposable);

            var results1      = scheduler.CreateObserver <int>();
            var subscription1 = default(IDisposable);

            var results2      = scheduler.CreateObserver <int>();
            var subscription2 = default(IDisposable);

            var results3      = scheduler.CreateObserver <int>();
            var subscription3 = default(IDisposable);

            scheduler.ScheduleAbsolute(100, () => subject      = new BehaviorSubject <int>(100));
            scheduler.ScheduleAbsolute(200, () => subscription = xs.Subscribe(subject));
            scheduler.ScheduleAbsolute(1000, () => subscription.Dispose());

            scheduler.ScheduleAbsolute(300, () => subscription1 = subject.Subscribe(results1));
            scheduler.ScheduleAbsolute(400, () => subscription2 = subject.Subscribe(results2));
            scheduler.ScheduleAbsolute(900, () => subscription3 = subject.Subscribe(results3));

            scheduler.ScheduleAbsolute(600, () => subscription1.Dispose());
            scheduler.ScheduleAbsolute(700, () => subscription2.Dispose());
            scheduler.ScheduleAbsolute(800, () => subscription1.Dispose());
            scheduler.ScheduleAbsolute(950, () => subscription3.Dispose());

            scheduler.Start();

            results1.Messages.AssertEqual(
                OnNext(300, 4),
                OnNext(340, 5),
                OnNext(410, 6),
                OnNext(520, 7)
                );

            results2.Messages.AssertEqual(
                OnNext(400, 5),
                OnNext(410, 6),
                OnNext(520, 7),
                OnCompleted <int>(630)
                );

            results3.Messages.AssertEqual(
                OnCompleted <int>(900)
                );
        }
コード例 #42
0
ファイル: Main.cs プロジェクト: kobi2294/MvvmKit
        public static void Run()
        {
            _container = new UnityContainer();
            _container.RegisterType <IResolver, UnityResolver>(new ContainerControlledLifetimeManager());
            _vm = _container.Resolve <ViewModel>();
            _vm.Items.CollectionChanged += (s, e) =>
            {
                Console.ForegroundColor = ConsoleColor.Cyan;
                Console.WriteLine($"Collection Changed: {e.AsString()}");
            };

            MvvmRx.ObserveMany(_vm, _vm.Items, item => item.DoMath, (item, number) => $"item: {item.Uid}, number: {number}")
            .Subscribe(val =>
            {
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine(val);
            }).DisposedBy(_vm);

            Console.WriteLine(_model.ToJson());

            _subj = new BehaviorSubject <ImmutableList <ItemModel> >(ImmutableList <ItemModel> .Empty);
            _vm.Initialize(_subj);

            _subj.ObserveDiff(m => m.Uid)
            .Subscribe(diff =>
            {
                Console.ForegroundColor = ConsoleColor.Yellow;
                Console.WriteLine(diff.ToJson());
            }).DisposedBy(_vm);

            _do(ImmutableList.Create(
                    new ItemModel("1", "First", "Odd"),
                    new ItemModel("2", "Second", "Even"),
                    new ItemModel("3", "Third", "Odd"),
                    new ItemModel("4", "Fourth", "Even"),
                    new ItemModel("5", "Fifth", "Odd")));

            var cmd3 = _vm.Items[2].DoMath;

            // 1, 2, 5, 4
            _do(_model
                .RemoveAt(2)
                .Move(2, 3));

            _vm.Items[1].DoMath.Execute(100);
            _vm.Items.Last().DoMath.Execute(200);

            // this should not do anything becuase the command is not in the loop anymore
            // since the owner of the command is disposed, this shoud throw an error
            try
            {
                cmd3.Execute(300);
            }
            catch (ObjectDisposedException ex)
            {
                Console.WriteLine("Thrown object disposed exception as expected");
            }


            // 6, 4
            _do(_model
                .SetItem(1, new ItemModel("6", "Sixth", "Even"))
                .Add(new ItemModel("7", "Seventh", "Odd"))
                .RemoveAll(m => m.Category == "Odd"));

            // 6*, 4
            _do(_model
                .SetItem(0, _model[0].With(x => x.DisplayName, "New Sixth").With(x => x.Category, "Edited"))
                .RemoveAt(1)
                .Insert(0, new ItemModel("4", "New Fourth", "Edited")));

            _vm.AddItem.Subscribe(x =>
            {
                _do(_model
                    .Add(new ItemModel((++_counter).ToString(), "Item " + _counter, "Category " + _counter)));
            },
                                  () => Console.WriteLine("Command Completed")
                                  );

            _vm.RemoveItem.Subscribe(id =>
            {
                _do(_model.RemoveAll(x => x.Uid == id));
            });


            _vm.AddItem.Execute(null);
            _vm.AddItem.Execute(null);
            _vm.RemoveItem.Execute("4");

            MvvmRx.ObservePropertyChanges(_vm, x => x.Caption)
            .Subscribe(x => Console.WriteLine($"Property Caption changed from {x.oldValue} to {x.newValue}"),
                       () => Console.WriteLine("Property observer completed"));

            // property changes observable should fire two events
            _vm.Caption = "A";
            _vm.Caption = "B";



            _vm.Dispose();
        }
コード例 #43
0
            protected void PrepareIsWelcome(bool isWelcome)
            {
                var subject = new BehaviorSubject <bool>(isWelcome);

                OnboardingStorage.IsNewUser.Returns(subject.AsObservable());
            }
コード例 #44
0
        public DmdDevice()
        {
            _currentFrameFormat    = new BehaviorSubject <FrameFormat>(FrameFormat.Rgb24);
            _vpmGray2Source        = new VpmGray2Source(_currentFrameFormat);
            _vpmGray4Source        = new VpmGray4Source(_currentFrameFormat);
            _vpmRgb24Source        = new VpmRgb24Source(_currentFrameFormat);
            _vpmAlphaNumericSource = new VpmAlphaNumericSource(_currentFrameFormat);

            AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;

            // setup logger
            var assembly      = Assembly.GetCallingAssembly();
            var assemblyPath  = Path.GetDirectoryName(new Uri(assembly.CodeBase).LocalPath);
            var logConfigPath = Path.Combine(assemblyPath, "DmdDevice.log.config");

            if (File.Exists(logConfigPath))
            {
                LogManager.Configuration = new XmlLoggingConfiguration(logConfigPath, true);
#if !DEBUG
                LogManager.Configuration.AddTarget("memory", MemLogger);
                LogManager.Configuration.LoggingRules.Add(new LoggingRule("*", LogLevel.Debug, MemLogger));
                LogManager.ReconfigExistingLoggers();
#endif
            }
#if !DEBUG
            else
            {
                SimpleConfigurator.ConfigureForTargetLogging(MemLogger, LogLevel.Debug);
            }
#endif
            CultureUtil.NormalizeUICulture();
            _config       = new Configuration();
            _altcolorPath = GetColorPath();

            // read versions from assembly
            var attr = assembly.GetCustomAttributes(typeof(AssemblyConfigurationAttribute), false);
            var fvi  = FileVersionInfo.GetVersionInfo(assembly.Location);
            _version = fvi.ProductVersion;
            if (attr.Length > 0)
            {
                var aca = (AssemblyConfigurationAttribute)attr[0];
                _sha = aca.Configuration;
                if (string.IsNullOrEmpty(_sha))
                {
                    _fullVersion = _version;
                }
                else
                {
                    _fullVersion = $"{_version} ({_sha})";
                }
            }
            else
            {
                _fullVersion = fvi.ProductVersion;
                _sha         = "";
            }

            Logger.Info("Starting VPinMAME API {0} through {1}.exe.", _fullVersion,
                        Process.GetCurrentProcess().ProcessName);
            Logger.Info("Assembly located at {0}", assembly.Location);
        }
コード例 #45
0
        public static void Initialize(IScheduler dispatcher)
        {
            Button.Implementation.Factory = (command, contentFactory, text, isDefault) =>
            {
                if (contentFactory != null)
                {
                    var states = new BehaviorSubject <ButtonStates>(ButtonStates.Unrooted);

                    var content = contentFactory(states.Switch());

                    var hittableContent = content.MakeHittable();

                    states.OnNext(new ButtonStates(
                                      isPressed: hittableContent.IsPressed(),
                                      isHovered: hittableContent.IsHovering(),
                                      isEnabled: command.IsEnabled));

                    hittableContent.Pressed.WithLatestFromBuffered(command.Execute, (evt, c) => c)
                    .ConnectWhile(content.IsRooted)
                    .Subscribe(action => dispatcher.Schedule(action));

                    return(hittableContent.Control);
                }
                else
                {
                    var width = new ReplaySubject <Points>(1);

                    return(Control.Create(self =>
                    {
                        Action action = () => { };


                        var b = new ObservableButton()
                        {
                            BezelStyle = NSBezelStyle.Rounded,
                        };

                        b.Activated += (s, a) => action();

                        if (isDefault)
                        {
                            b.WindowObservable
                            .Where(window => window != null)
                            .Subscribe(window =>
                                       Fusion.Application.MainThread.InvokeAsync(() => window.DefaultButtonCell = b.Cell));
                        }

                        command.Action
                        .CombineLatest(text)
                        .Take(1)
                        .ObserveOn(dispatcher)
                        .Subscribe(
                            cmdText =>
                        {
                            UpdateButtonFields(b, cmdText.Item1.HasValue, cmdText.Item2, width);
                        });

                        self.BindNativeProperty(
                            dispatcher,
                            "command",
                            command.Action.CombineLatest(text),
                            cmdText =>
                        {
                            UpdateButtonFields(b, cmdText.Item1.HasValue, cmdText.Item2, width);
                            action = () => cmdText.Item1.Do(x => x());
                        });

                        self.BindNativeDefaults(b, dispatcher);

                        return b;
                    })
                           .WithHeight(32)
                           .WithWidth(width));
                }
            };
        }
コード例 #46
0
ファイル: ObservableValue.cs プロジェクト: yt4687/TVTComment
 public ObservableValue(T initialValue = default(T))
 {
     subject           = new BehaviorSubject <T>(Value);
     this.initialValue = initialValue;
     Value             = initialValue;
 }
コード例 #47
0
 public ImageSourceBitmap(BitmapSource bmp)
 {
     SetDimensions(bmp.PixelWidth, bmp.PixelHeight);
     _frames = new BehaviorSubject <BitmapSource>(bmp);
 }
コード例 #48
0
        /// <summary>
        /// Demonstrates various rendering capabilities.
        /// </summary>
        /// <param name="sample">&lt;colors|dir&gt; Renders a specified sample</param>
        /// <param name="height">The height of the rendering area</param>
        /// <param name="width">The width of the rendering area</param>
        /// <param name="top">The top position of the render area</param>
        /// <param name="left">The left position of the render area</param>
        /// <param name="virtualTerminalMode">Enable virtual terminal mode</param>
        /// <param name="text">The text to render</param>
        /// <param name="outputMode">&lt;Ansi|NonAnsi|File&gt; Sets the output mode</param>
        /// <param name="overwrite">Overwrite the specified region. (If not, scroll.)</param>
        public static void Main(
            SampleName sample        = SampleName.Dir,
            int?height               = null,
            int?width                = null,
            int top                  = 0,
            int left                 = 0,
            bool virtualTerminalMode = true,
            string text              = null,
            OutputMode outputMode    = OutputMode.Auto,
            bool overwrite           = true,
#pragma warning disable CS1573 // Parameter has no matching param tag in the XML comment (but other parameters do)
            IConsole console = null)
#pragma warning restore CS1573 // Parameter has no matching param tag in the XML comment (but other parameters do)
        {
            var region = new Region(left,
                                    top,
                                    width ?? Console.WindowWidth,
                                    height ?? Console.WindowHeight,
                                    overwrite);

            var terminal = console as ITerminal;

            if (terminal != null && overwrite)
            {
                terminal.Clear();
            }

            var consoleRenderer = new ConsoleRenderer(
                console,
                mode: outputMode,
                resetAfterRender: true);

            switch (sample)
            {
            case SampleName.Colors:
            {
                var screen = new ScreenView(renderer: consoleRenderer);
                screen.Child = new ColorsView(text ?? "*");

                screen.Render(region);
            }
            break;

            case SampleName.Dir:
                var directoryTableView = new DirectoryTableView(new DirectoryInfo(Directory.GetCurrentDirectory()));
                directoryTableView.Render(consoleRenderer, region);

                break;

            case SampleName.Moby:
                consoleRenderer.RenderToRegion(
                    $"Call me {StyleSpan.BoldOn()}{StyleSpan.UnderlinedOn()}Ishmael{StyleSpan.UnderlinedOff()}{StyleSpan.BoldOff()}. Some years ago -- never mind how long precisely -- having little or no money in my purse, and nothing particular to interest me on shore, I thought I would sail about a little and see the watery part of the world. It is a way I have of driving off the spleen and regulating the circulation. Whenever I find myself growing grim about the mouth; whenever it is a damp, drizzly November in my soul; whenever I find myself involuntarily pausing before coffin warehouses, and bringing up the rear of every funeral I meet; and especially whenever my hypos get such an upper hand of me, that it requires a strong moral principle to prevent me from deliberately stepping into the street, and {ForegroundColorSpan.Rgb(60, 0, 0)}methodically{ForegroundColorSpan.Reset()} {ForegroundColorSpan.Rgb(90, 0, 0)}knocking{ForegroundColorSpan.Reset()} {ForegroundColorSpan.Rgb(120, 0, 0)}people's{ForegroundColorSpan.Reset()} {ForegroundColorSpan.Rgb(160, 0, 0)}hats{ForegroundColorSpan.Reset()} {ForegroundColorSpan.Rgb(220, 0, 0)}off{ForegroundColorSpan.Reset()} then, I account it high time to get to sea as soon as I can. This is my substitute for pistol and ball. With a philosophical flourish Cato throws himself upon his sword; I quietly take to the ship. There is nothing surprising in this. If they but knew it, almost all men in their degree, some time or other, cherish very nearly the same feelings towards the ocean with me.",
                    region);
                break;

            case SampleName.Processes:
            {
                var view = new ProcessesView(Process.GetProcesses());
                view.Render(consoleRenderer, region);
            }

            break;

            case SampleName.TableView:
            {
                var table = new TableView <Process>
                {
                    Items = Process.GetProcesses().Where(x => !string.IsNullOrEmpty(x.MainWindowTitle)).OrderBy(p => p.ProcessName).ToList()
                };
                table.AddColumn(process => $"{process.ProcessName} ", "Name");
                table.AddColumn(process => ContentView.FromObservable(process.TrackCpuUsage(), x => $"{x.UsageTotal:P}"), "CPU", ColumnDefinition.Star(1));

                var screen = new ScreenView(renderer: consoleRenderer)
                {
                    Child = table
                };
                screen.Render();
            }
            break;

            case SampleName.Clock:
            {
                var screen          = new ScreenView(renderer: consoleRenderer);
                var lastTime        = DateTime.Now;
                var clockObservable = new BehaviorSubject <DateTime>(lastTime);
                var clockView       = ContentView.FromObservable(clockObservable, x => $"{x:T}");
                screen.Child = clockView;
                screen.Render();

                while (!Console.KeyAvailable)
                {
                    if (DateTime.Now - lastTime > TimeSpan.FromSeconds(1))
                    {
                        lastTime = DateTime.Now;
                        clockObservable.OnNext(lastTime);
                    }
                }
            }
            break;

            case SampleName.GridLayout:
            {
                var screen  = new ScreenView(renderer: consoleRenderer);
                var content = new ContentView(
                    "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum for Kevin.");
                var smallContent = new ContentView("Kevin Bost");
                var longContent  = new ContentView("Hacking on System.CommandLine");

                var gridView = new GridView();
                gridView.SetColumns(
                    ColumnDefinition.SizeToContent(),
                    ColumnDefinition.Star(1),
                    ColumnDefinition.Star(0.5)
                    );
                gridView.SetRows(
                    RowDefinition.Star(0.5),
                    RowDefinition.Star(0.5)
                    );

                gridView.SetChild(smallContent, 0, 0);
                gridView.SetChild(longContent, 0, 1);
                //gridView.SetChild(content, 0, 0);
                gridView.SetChild(content, 1, 1);
                gridView.SetChild(content, 2, 0);

                screen.Child = gridView;

                screen.Render();
            }
            break;

            default:
                if (!string.IsNullOrWhiteSpace(text))
                {
                    consoleRenderer.RenderToRegion(
                        text,
                        region);
                }
                else
                {
                    var screen      = new ScreenView(renderer: consoleRenderer);
                    var stackLayout = new StackLayoutView();
                    var content1    = new ContentView("Hello World!");
                    var content2    = new ContentView(
                        "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum for Kevin.");
                    stackLayout.Add(content2);
                    stackLayout.Add(content1);
                    stackLayout.Add(content2);
                    screen.Child = stackLayout;
                    screen.Render(new Region(0, 0, 50, Size.MaxValue));
                    //screen.Render(writer);
                }

                break;
            }

            if (!Console.IsOutputRedirected)
            {
                Console.ReadKey();
            }
        }
コード例 #49
0
 public ImageSourceGray4(BitmapSource bmp)
 {
     SetDimensions(bmp.PixelWidth, bmp.PixelHeight);
     _frames = new BehaviorSubject <DMDFrame>(_dmdFrame.Update(bmp.PixelWidth, bmp.PixelHeight, ImageUtil.ConvertToGray4(bmp)));
 }
コード例 #50
0
 /// <inheritdoc />
 protected BaseEditableGuiEntry(MakerCategory category, TValue initialValue, BaseUnityPlugin owner) : base(category, owner)
 {
     _incomingValue = new BehaviorSubject <TValue>(initialValue);
     _outgoingValue = new Subject <TValue>();
 }
コード例 #51
0
        public void Control_With_Animated_Opacity_And_Children_Should_Start_New_Layer()
        {
            using (UnitTestApplication.Start(TestServices.MockPlatformRenderInterface))
            {
                Decorator decorator;
                Border    border;
                Canvas    canvas;
                var       tree = new TestRoot
                {
                    Padding = new Thickness(10),
                    Width   = 100,
                    Height  = 120,
                    Child   = decorator = new Decorator
                    {
                        Padding = new Thickness(11),
                        Child   = border = new Border
                        {
                            Background = Brushes.Red,
                            Padding    = new Thickness(12),
                            Child      = canvas = new Canvas()
                        }
                    }
                };

                var layout = tree.LayoutManager;
                layout.ExecuteInitialLayoutPass();

                var animation = new BehaviorSubject <double>(0.5);
                border.Bind(Border.OpacityProperty, animation, BindingPriority.Animation);

                var scene        = new Scene(tree);
                var sceneBuilder = new SceneBuilder();
                sceneBuilder.UpdateAll(scene);

                var rootNode   = (VisualNode)scene.Root;
                var borderNode = (VisualNode)scene.FindNode(border);
                var canvasNode = (VisualNode)scene.FindNode(canvas);

                Assert.Same(tree, rootNode.LayerRoot);
                Assert.Same(border, borderNode.LayerRoot);
                Assert.Same(border, canvasNode.LayerRoot);
                Assert.Equal(0.5, scene.Layers[border].Opacity);

                Assert.Equal(2, scene.Layers.Count());
                Assert.Empty(scene.Layers.Select(x => x.LayerRoot).Except(new IVisual[] { tree, border }));

                animation.OnCompleted();
                scene = scene.CloneScene();

                sceneBuilder.Update(scene, border);

                rootNode   = (VisualNode)scene.Root;
                borderNode = (VisualNode)scene.FindNode(border);
                canvasNode = (VisualNode)scene.FindNode(canvas);

                Assert.Same(tree, rootNode.LayerRoot);
                Assert.Same(tree, borderNode.LayerRoot);
                Assert.Same(tree, canvasNode.LayerRoot);
                Assert.Single(scene.Layers);

                var rootDirty = scene.Layers[tree].Dirty;

                Assert.Single(rootDirty);
                Assert.Equal(new Rect(21, 21, 58, 78), rootDirty.Single());
            }
        }
コード例 #52
0
 public VpmAlphaNumericSource(BehaviorSubject <FrameFormat> lastFrameFormat)
 {
     _framesAlphaNumeric = new Subject <AlphaNumericFrame>();
     _lastFrameFormat    = lastFrameFormat;
 }
        public EventStoreConnectionStatusMonitor(IEventStoreConnection connection, ILoggerFactory?loggerFactory = null)
        {
            _eventStoreConnection = connection;

            _logger = loggerFactory?.CreateLogger(nameof(EventStoreConnectionStatusMonitor));

            _isConnected = new BehaviorSubject <bool>(false);

            var connected = Observable.FromEventPattern <ClientConnectionEventArgs>(h => connection.Connected += h, h => connection.Connected -= h).Select(_ =>
            {
                return(ConnectionStatus.Connected);
            });

            var disconnected = Observable.FromEventPattern <ClientConnectionEventArgs>(h => connection.Disconnected += h, h => connection.Disconnected -= h).Select(arg =>
            {
                _logger?.LogInformation($"{nameof(EventStoreConnectionStatusMonitor)} => Connection lost - [{arg.EventArgs.RemoteEndPoint}]");

                return(ConnectionStatus.Disconnected);
            });

            var reconnecting = Observable.FromEventPattern <ClientReconnectingEventArgs>(h => connection.Reconnecting += h, h => connection.Reconnecting -= h).Select(_ =>
            {
                return(ConnectionStatus.Connecting);
            });

            var closed = Observable.FromEventPattern <ClientClosedEventArgs>(h => connection.Closed += h, h => connection.Closed -= h).Select(arg =>
            {
                _logger?.LogInformation($"{nameof(EventStoreConnectionStatusMonitor)} => Connection closed - [{arg.EventArgs.Reason}]");

                return(ConnectionStatus.Closed);
            });

            var errorOccurred = Observable.FromEventPattern <ClientErrorEventArgs>(h => connection.ErrorOccurred += h, h => connection.ErrorOccurred -= h).Select(arg =>
            {
                _logger?.LogError(arg.EventArgs.Exception, $"{nameof(EventStoreConnectionStatusMonitor)} => An error occured while connected to EventStore");

                return(ConnectionStatus.ErrorOccurred);
            });

            var authenticationFailed = Observable.FromEventPattern <ClientAuthenticationFailedEventArgs>(h => connection.AuthenticationFailed += h, h => connection.AuthenticationFailed -= h).Select(arg =>
            {
                _logger?.LogError($"{nameof(EventStoreConnectionStatusMonitor)} => Authentication failed while connecting to EventStore - [{arg.EventArgs.Reason}]");

                return(ConnectionStatus.AuthenticationFailed);
            });

            _connectionInfoChanged = Observable.Merge(connected, disconnected, reconnecting, closed, errorOccurred, authenticationFailed)
                                     .Scan(ConnectionInfo.InitialDisconnected, UpdateConnectionInfo)
                                     .StartWith(ConnectionInfo.InitialDisconnected)
                                     .Do(connectionInfo =>
            {
                ConnectionInfo = connectionInfo;
                _logger?.LogInformation($"{nameof(EventStoreConnectionStatusMonitor)} => ConnectionInfo - {connectionInfo}");
                _isConnected.OnNext(connectionInfo.Status == ConnectionStatus.Connected);
            })
                                     .Replay(1);

            _cleanUp = _connectionInfoChanged.Connect();

            _eventStoreConnection.ConnectAsync().Wait();
        }
コード例 #54
0
 public PersistentProperty(PersistentSettings settings, string name, Optional <T> value)
 {
     _settings = settings;
     _name     = name;
     _value    = new BehaviorSubject <Optional <T> >(value);
 }
コード例 #55
0
 public BroadcastListener()
 {
     _activity = CrossCurrentActivity.Current.Activity;
     _activity.RegisterReceiver(this, new IntentFilter(BluetoothAdapter.ActionStateChanged));
     StateUpdatedSubject = new BehaviorSubject <ManagerState>(BluetoothAdapter.DefaultAdapter?.State.ToManagerState() ?? ManagerState.Unsupported);
 }
コード例 #56
0
 public BehaviorSubjectWrapper(BehaviorSubject <T> subject)
 {
     _subject = subject;
 }
コード例 #57
0
 public FilterWithObservable()
 {
     _source  = new SourceList <Person>();
     _filter  = new BehaviorSubject <Func <Person, bool> >(p => p.Age > 20);
     _results = _source.Connect().Filter(_filter).AsAggregator();
 }
コード例 #58
0
        public void Value_Initial()
        {
            var s = new BehaviorSubject <int>(42);

            Assert.AreEqual(42, s.Value);
        }
コード例 #59
0
 /// <param name="observable">Observable of the readonly model object. Any updates to this will trigger <see cref="ModelUpdatedImpl"/></param>
 protected ObservableViewModel(BehaviorSubject <TModel> observable)
 {
     Observable = observable;
     Initialize();
     TrackDisposable(Observable.Subscribe(ModelUpdated));
 }
コード例 #60
0
 public static Command Toggle(this BehaviorSubject <bool> self)
 {
     return(Command.Enabled(() => self.OnNext(!self.Value)));
 }