Esempio n. 1
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));
 }
Esempio n. 2
0
        public void TestOnError()
        {
            var expectedOnNext = new List <int> {
                7, 1, 10, 100
            };
            var onNext               = new List <int>();
            var exceptions           = new List <Exception>();
            var onCompletedCallCount = 0;
            var subject              = new BehaviorSubject <int>(7);

            subject.Subscribe(x => onNext.Add(x), x => exceptions.Add(x), () => onCompletedCallCount++);

            subject.OnNext(1);
            subject.OnNext(10);
            subject.OnNext(100);
            Assert.That(onNext, Is.EqualTo(expectedOnNext));
            Assert.That(exceptions, Has.Count.EqualTo(0));
            Assert.That(onCompletedCallCount, Is.EqualTo(0));

            subject.OnError(new Exception());
            Assert.That(exceptions, Has.Count.EqualTo(1));

            subject.OnNext(1);
            subject.OnNext(10);
            subject.OnNext(200);
            Assert.That(onNext, Is.EqualTo(expectedOnNext));
            Assert.That(onCompletedCallCount, Is.EqualTo(0));
        }
Esempio n. 3
0
        public static void BehaviorSubject()
        {
            Console.WriteLine("----------BEHAVIOR SUBJECT");
            var subject = new BehaviorSubject <int>(10000);

            subject.Subscribe(new Observer("A"));
            subject.OnNext(1);
            subject.OnNext(11);
            subject.OnNext(111);
            subject.Subscribe(new Observer("B"));
            subject.OnNext(2);
            subject.OnNext(3);
            subject.OnCompleted();
            subject.OnNext(4);
            Console.ReadKey();
        }
        private ShellViewModel()
        {
            FilePath = new BehaviorSubject <string>(@"Test.mrpd");
            this.WhenActivated(d =>
            {
                TestCommand = ReactiveCommand.Create(() =>
                {
                    TestName = "Test";
                });

                (LoadFileCommand = ReactiveCommand.Create(LoadFile)).DisposeWith(d);
                (UpCommand = ReactiveCommand.Create(Up, this.WhenAnyValue(s => s.SelectedNodeIndex).Select(i => i > 0))).DisposeWith(d);
                (CreateNodeCommand = ReactiveCommand.Create(CreateNode)).DisposeWith(d);
                (_deleteNodeCommand = ReactiveCommand.Create <string>(DeleteNode)).DisposeWith(d);
                (_enterNodeCommand = ReactiveCommand.Create <string>(EnterNode)).DisposeWith(d);
                (_startRenameNodeCommand = ReactiveCommand.Create <string>(StartRenameNode)).DisposeWith(d);
                (_endRenameNodeCommand = ReactiveCommand.Create <(string, string)>(EndRenameNode)).DisposeWith(d);
                (_deleteDataCommand = ReactiveCommand.Create <string>(DeleteData)).DisposeWith(d);
                NodeNameList.Connect().ObserveOnDispatcher(DispatcherPriority.Background).Bind(out _nodeNames).Subscribe().DisposeWith(d);
                NodeItemViewModelCache.Connect().Sort(SortExpressionComparer <ItemViewModelBase> .Ascending(i => i.Name)).Concat(DataItemViewModelCache.Connect().Sort(SortExpressionComparer <ItemViewModelBase> .Ascending(i => i.Name))).Bind(out _itemViewModels).Subscribe().DisposeWith(d);
                this.WhenAnyValue(s => s.SelectedNodeIndex).Skip(1).Subscribe(SelectedNodeIndexChanged).DisposeWith(d);
                FilePath.Subscribe(FilePathChanged).DisposeWith(d);
                FilePath.Select(f => f != null).ToProperty(this, s => s.HasFile, out _hasFile).DisposeWith(d);

                (SaveCommand = ReactiveCommand.Create(async() =>
                {
                    await this.ShowProgressAsync("", "正在保存...");
                })).DisposeWith(d);
            });
        }
        static void BehaviorSubjectExample1()
        {
            //Need to provide a default value.
            var subject = new BehaviorSubject <string>("a");

            subject.Subscribe(Console.WriteLine);
        }
        static void BehaviorSubjectExample2()
        {
            var subject = new BehaviorSubject <string>("a");

            subject.OnNext("b");
            subject.Subscribe(Console.WriteLine);
        }
        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);
        }
Esempio n. 8
0
 public static void BehaviorSubjectExample3()
 {
     var subject = new BehaviorSubject<string>("a");
     subject.OnNext("b");
     subject.Subscribe(Console.WriteLine);
     subject.OnNext("c");
     subject.OnNext("d");
 }
Esempio n. 9
0
        static void Main(string[] args)
        {
            //Need to provide a default value.
            var subject = new BehaviorSubject <string>("a");

            subject.Subscribe(Console.WriteLine);
            Console.Read();
        }
Esempio n. 10
0
        static void Main(string[] args)
        {
            var subject = new BehaviorSubject <string>("a");

            subject.OnNext("b");
            subject.Subscribe(Console.WriteLine);
            Console.Read();
        }
Esempio n. 11
0
 public static void BehaviorSubjectTest()
 {
     using var subject = new BehaviorSubject <string>("a");
     subject.OnNext("b");
     subject.OnNext("c");
     subject.Subscribe(Console.WriteLine);
     subject.OnNext("d");
 }
Esempio n. 12
0
    static ApiWrapper()
    {
        var req    = new UnityWebRequest(HTTP_PROTOCOL + URL);
        var cookie = req.GetRequestHeader("Cookie");

        Cookie = new BehaviorSubject <string>(string.IsNullOrEmpty(cookie) ? "" : cookie);
        Cookie.Subscribe(Debug.Log);
    }
Esempio n. 13
0
        /// <inheritdoc />
        protected override void Start()
        {
            base.Start();
            CurrentCoordinate.Subscribe(_ => StartCoroutine(OnDataChangedCo()));
#if KK // hs2 ais is HScene //todo KKS full game
            _isDuringHScene = "H".Equals(Scene.Instance.LoadSceneName, StringComparison.Ordinal);
#endif
        }
Esempio n. 14
0
        public void Setup()
        {
            var subject = new BehaviorSubject <Progress>(new Progress());

            reporter = new ProgressReporter(subject);
            reports  = new List <Progress>();
            subject.Subscribe(reports.Add);
        }
Esempio n. 15
0
        /// <summary>
        ///
        /// </summary>
        public override void Enable()
        {
            undoCommand = new VisualDelegateCommand(Undo, "Undo",
                                                    ImageFactory.GetImageThisAssembly("Images/arrow-undo-16.png"),
                                                    ImageFactory.GetImageThisAssembly("Images/arrow-undo-32.png"),
                                                    false);

            redoCommand = new VisualDelegateCommand(Redo, "Redo",
                                                    ImageFactory.GetImageThisAssembly("Images/arrow-redo-16.png"),
                                                    ImageFactory.GetImageThisAssembly("Images/arrow-redo-32.png"),
                                                    false);

            var group = IrAuthorShell.HomeTab.GetGroup("Clipboard");

            group.AddButton(undoCommand);
            group.AddButton(redoCommand);

            var deleteStream = Observable.FromEventPattern <CancelEventArgs <RuleRepositoryDefBase> >(
                x => RuleApplicationService.Controller.RemovingDef += x,
                x => RuleApplicationService.Controller.RemovingDef -= x)
                               .Select(x => x.EventArgs.Item)
                               .Select(x => PopulateUndoHistoryItem(x, UndoDefRemoved));

            var insertStream = Observable.FromEventPattern <EventArgs <RuleRepositoryDefBase> >(
                x => RuleApplicationService.Controller.DefAdded += x,
                x => RuleApplicationService.Controller.DefAdded -= x)
                               .Select(x => x.EventArgs.Item)
                               .Select(x => PopulateUndoHistoryItem(x, UndoDefInserted));


            // add operations to the undo stack, as long as there isn't an undo currently in progress
            var operationStream = deleteStream.Merge(insertStream);
            var undoStream      = operationStream.Where(x => !undoInProgress.Value).Do(item => LogEvent("UndoStream: {0}", item.DefToUndo.Name));
            var redoStream      = operationStream.Where(x => undoInProgress.Value).Do(item => LogEvent("RedoStream: {0}", item.DefToUndo.Name));

            subscriptionsDisposable.Add(undoStream.Subscribe(x => undoBuffer.Push(x)));
            subscriptionsDisposable.Add(redoStream.Subscribe(x => redoBuffer.Push(x)));

            subscriptionsDisposable.Add(redoBuffer.ItemCount.Subscribe(x => redoCommand.IsEnabled = x > 0));

            var undoActionStream = UndoClicked.Where(x => undoBuffer.Any());

            subscriptionsDisposable.Add(undoActionStream.Subscribe(x =>
            {
                var item = undoBuffer.Pop();
                PerformUndo(item);
            }, exception => LogEvent(exception.ToString())));

            var redoActionStream = redoSubject.Where(x => redoBuffer.Any());

            subscriptionsDisposable.Add(redoActionStream.Subscribe(x =>
            {
                var item = redoBuffer.Pop();
                item.UndoAction(item);
            }));
            subscriptionsDisposable.Add(undoBuffer.ItemCount.Subscribe(x => undoCommand.IsEnabled = x > 0));
            subscriptionsDisposable.Add(undoInProgress.Subscribe(x => LogEvent("UndoInProgress: {0}", x)));
        }
Esempio n. 16
0
 static void Example4()
 {
     var subject = new BehaviorSubject<string>("a");
       subject.OnNext("b");
       subject.OnNext("c");
       subject.OnNext("d");
       subject.OnCompleted();
       subject.Subscribe(Console.WriteLine);
 }
Esempio n. 17
0
        static void Main(string[] args)
        {
            var sub = new  BehaviorSubject <string>("sfsrf");

            sub.Subscribe(value => Console.WriteLine(value));
            sub.OnNext("hello");
            sub.OnNext("hiii");
            Console.ReadLine();
        }
        public void BehaviorSubjectCompletedExample()
        {
            var subject = new BehaviorSubject <string>("a");

            subject.OnNext("b");
            subject.OnNext("c");
            subject.OnCompleted();
            subject.Subscribe(Console.WriteLine);
        }
Esempio n. 19
0
        private static void BehaviorSubjectCompletedExample()
        {
            var subject = new BehaviorSubject <string>("a");

            subject.OnNext("b");
            subject.OnNext("c");
            subject.OnCompleted();//completed before subscribe was set
            subject.Subscribe(Console.WriteLine);
        }
Esempio n. 20
0
        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();
                });
        }
Esempio n. 21
0
        public async Task StartAsync(CancellationToken cancellationToken)
        {
            _tokenSource = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
            await InitWorker().ConfigureAwait(false);

            Observable
            .Generate(
                _counter,
                x => !_tokenSource.IsCancellationRequested,
                x => _counter++,
                x => x,
                x => TimeSpan.FromSeconds(10),
                _scheduler)
            .Subscribe(
                async x => await DoWork(x).ConfigureAwait(false),
                ex => Logger.LogError(ex, "DoWork: Unknown exception"),
                () =>
            {
                _mainSubscriptionCompleted = true;
                Logger.LogInformation("Main Subscription completed");
            },
                _tokenSource.Token
                );

            _subject
            //.TakeLast(1)
            .Subscribe(
                x =>
            {
                try
                {
                    //if (_looker == 1)
                    //{
                    //    return;
                    //}
                    Interlocked.Exchange(ref _looker, 1);
                    x.ForEachAsync(MaxDop, ProcessDataAsync).Wait();
                }
                catch (Exception ex)
                {
                    Logger.LogError(ex, "Unknown exception");
                }
                Interlocked.Exchange(ref _looker, 0);
            },
                ex =>
            {
                Logger.LogError(ex, "ProcessDataAsync: Unknown exception");
            },
                () =>
            {
                _processingSubscriptionCompleted = true;
                Logger.LogInformation("Processing Subscription completed");
            },
                _tokenSource.Token
                );
        }
Esempio n. 22
0
        protected internal DMLTriggerListener(Schema schema)
        {
            _schema = schema;
            _connectionStateChangeSubject = new BehaviorSubject <ListeningConnectionState>(ListeningConnectionState.New);
            _connectionStateChangeSubject.Subscribe(async state => await OnConnectionStateChanges(state));

            _tokenSource = new CancellationTokenSource();

            InitCommands();
        }
Esempio n. 23
0
            public IDisposable Subscribe(IObserver <TModel> observer)
            {
                var subscription = _observable.Subscribe(observer);

                return(Disposable.Create(() =>
                {
                    subscription.Dispose();
                    _factory.OnStreamUnsubscribed(this);
                }));
            }
Esempio n. 24
0
    void Start()
    {
        var subject = new BehaviorSubject <int>(5);

        subject.Subscribe(x => Debug.Log(x));

        subject.OnNext(1);
        subject.OnNext(2);
        subject.OnNext(3);
    }
Esempio n. 25
0
 public ActiveDownload(IConnectableObservable <DownloadProgress> downloadProgress, Action completed, string name)
 {
     Name = name;
     LogTo.Verbose("[{download}] Created ActiveDownload", Name);
     disposable.Add(downloadProgress.Subscribe(progress));
     disposable.Add(downloadProgress.Connect());
     disposable.Add(progress.DistinctUntilChanged(dp => dp.State).Subscribe(dp =>
                                                                            LogTo.Verbose("[{download}] State changed to {state}", Name, dp.State)));
     disposable.Add(progress.Subscribe(_ => { }, completed));
 }
Esempio n. 26
0
        private static void Step4()
        {
            var subject = new BehaviorSubject <string>("x");

            subject.Subscribe(s => WriteLine($"Subscriber A: {s}"), () => WriteLine("Subscriber A Completed!"));
            subject.Subscribe(s => WriteLine($"Subscriber B: {s}"), () => WriteLine("Subscriber B Completed!"));

            var list = Enumerable
                       .Range(1, 5)
                       .Select(i => i.ToString())
                       .ToList();

            WriteLine("\nFirst push\n");
            list.ForEach(s => subject.OnNext($"1-{s}"));

            subject.Subscribe(s => WriteLine($"Subscriber C: {s}"), () => WriteLine("Subscriber C Completed!"));

            WriteLine("\nSecond push\n");
            list.ForEach(s => subject.OnNext($"2-{s}"));
        }
 public RenderGraphCollection Init()
 {
     if (_renderer != null)
     {
         _renderer.Init();
         return(this);
     }
     _resizableDestinations.ForEach(dest => _dimensions.Subscribe(dim => dest.SetDimensions(dim.Width, dim.Height)));
     _converters.ForEach(converter => converter.Init());
     return(this);
 }
Esempio n. 28
0
        private static void behaviourSubject()
        {
            ISubject <int> s = new BehaviorSubject <int>(0);

            Console.WriteLine("Adding values");
            s.OnNext(2);
            Console.WriteLine("Adding next value");
            s.OnNext(4);
            s.Subscribe(Console.WriteLine);
            s.OnNext(6);
        }
Esempio n. 29
0
        public static void BehaviorSubject_DefaultValue()
        {
            var recorder = new RecordObserver();

            ISubject <int> subject = new BehaviorSubject <int>(101);

            subject.Subscribe(recorder);

            Assert.AreEqual(1, recorder.NumOfNextInvoke);
            Assert.AreEqual(101, recorder.LastValue);
            Assert.IsFalse(recorder.IsCompleted);
        }
Esempio n. 30
0
        public void replays_error_sequence()
        {
            BehaviorSubject <int> subject = new BehaviorSubject <int>(0);

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

            subject.OnError(new Exception());

            subject.Subscribe(stats);

            Assert.IsTrue(stats.ErrorCalled);
        }
Esempio n. 31
0
        public void BindIntents()
        {
            _disposables.Add(_viewState.Subscribe(state => _view.Render(state)));

            _disposables.Add(
                _view.SearchIntent()
                .SelectMany(query => _searchUseCase.Search(query))
                .SubscribeOn(TaskPoolScheduler.Default)
                .ObserveOn(SynchronizationContext.Current)
                .Subscribe(state => _viewState.OnNext(state))
                );
        }
Esempio n. 32
0
        public void replays_empty_sequence()
        {
            BehaviorSubject <int> subject = new BehaviorSubject <int>(0);

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

            subject.OnCompleted();

            subject.Subscribe(stats);

            Assert.AreEqual(0, stats.NextCount);
            Assert.IsTrue(stats.CompletedCalled);
        }
        public void BehaviorSubjectExample3()
        {
            var subject = new BehaviorSubject <string>("a");

            subject.OnNext("b");
            subject.Subscribe(Console.WriteLine);
            subject.OnNext("c");
            subject.OnNext("d");

            //b
            //c
            //d
        }
Esempio n. 34
0
        public void SubjectsTest()
        {
            {
                int count = 0;

                // 最後に発行された値をキャッシュし、後からSubscribeされたときにその値を発行
                var behaviourSubject = new BehaviorSubject <int>(1);
                behaviourSubject.Subscribe(num => count += num);

                Assert.AreEqual(1, count, "初期値が発行されて1");
            }

            {
                int count = 0;

                // 最後に発行された値をキャッシュし、後からSubscribeされたときにその値を発行
                var behaviourSubject = new BehaviorSubject <int>(1);
                behaviourSubject.OnNext(2);
                behaviourSubject.Subscribe(num => count += num);

                Assert.AreEqual(2, count, "最後に発行された値がキャッシュされ、後のSubscribeで呼び出される");
            }

            {
                int count = 0;

                // 過去全ての発行された値をキャッシュし、あとからSubscribeされたときにその値をすべてまとめて発行する
                var replaySubject = new ReplaySubject <int>();
                replaySubject.OnNext(1);
                replaySubject.OnNext(1);
                replaySubject.Subscribe(num => count += num);

                Assert.AreEqual(2, count, "過去に発行された値がすべて呼び出されて2");
            }

            {
                int count = 0;

                // OnNextを直ちに発行せずに内部でキャッシュしてOnCompletedが実行されたタイミングで、最後のOnNextを一つだけ発行する
                var asyncSubject = new AsyncSubject <int>();
                asyncSubject.OnNext(1);
                asyncSubject.OnNext(2);
                asyncSubject.OnNext(3);

                asyncSubject.Subscribe(num => count += num);
                Assert.AreEqual(0, count, "まだOnNextは呼びだれていないので0");

                asyncSubject.OnCompleted();
                Assert.AreEqual(3, count, "OnCompletedが呼び出され、最後のOnNextが一つだけ発行されて3");
            }
        }
        private void Start()
        {
            //BehaviorSubjectは初期値を設定できる
            behaviorSubject = new BehaviorSubject<int>(0);

            /*
            OnNext → Subscribe と実行し、Subscribeした瞬間に直前の値が発行されることを確認しよう
            */

            // Subscribeボタンが押されたらSubjectをSubscribeしてresultTextに表示する
            subscribeButton.OnClickAsObservable().Subscribe(_ =>
            {
                if (behaviorSubject != null)
                {
                    behaviorSubject.Subscribe(
                        time => resultText.text += time.ToString() + " ", //OnNext
                        () => resultText.text += "OnCompleted "); //OnCompleted
                }
            });

            // OnNextボタンが押されたら今が何度目のOnNextであるかを発行する
            onNextButton.OnClickAsObservable().Subscribe(_ =>
            {
                if (behaviorSubject != null)
                {
                    behaviorSubject.OnNext(++onNextCount);
                }
            });

            // OnCompletedボタンが押されたらOnCompletedを発行する
            onCompletedButton.OnClickAsObservable().Subscribe(_ =>
            {
                if (behaviorSubject != null)
                {
                    behaviorSubject.OnCompleted();
                }
            });

            // Resetボタンが押されたら全体を初期化する
            resetButton.OnClickAsObservable().Subscribe(_ =>
            {
                if (behaviorSubject != null)
                {
                    behaviorSubject.OnCompleted();
                }
                behaviorSubject = new BehaviorSubject<int>(0);
                resultText.text = "";
                onNextCount = 0;
            });
        }
Esempio n. 36
0
        public void only_replays_one_value()
        {
            BehaviorSubject <int> subject = new BehaviorSubject <int>(0);

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

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

            subject.Subscribe(stats);

            Assert.AreEqual(1, stats.NextCount);
            Assert.IsTrue(stats.NextValues.SequenceEqual(new int[] { 2 }));
        }
Esempio n. 37
0
        public void errors_are_sent_through_scheduler()
        {
            ManualScheduler scheduler = new ManualScheduler();

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

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

            subject.OnError(new Exception());

            subject.Subscribe(stats);

            Assert.IsFalse(stats.ErrorCalled);

            scheduler.RunNext();
            Assert.IsTrue(stats.ErrorCalled);
        }
Esempio n. 38
0
        static void Main(string[] args)
        {
            var serviceClient = new JsonRestClientAsync("http://g-un--:1337/");
            var responseSubject = new BehaviorSubject<Unit>(Unit.Default);

            responseSubject.Subscribe(_ =>
                {
                    serviceClient.PostAsync<ResourceResponse>(
                        "/async",
                        new ResourceRequest()
                        {
                            ResourceKey = Guid.NewGuid().ToString()
                        },
                        response =>
                        {
                            Console.WriteLine("Data received");
                            Console.WriteLine(response.ResourceData);
                            responseSubject.OnNext(Unit.Default);
                        },
                        (response, ex) =>
                        {
                            Console.WriteLine("Exception on calling service post method");
                            Console.WriteLine(ex);
                            responseSubject.OnCompleted();
                        });
                });

            Observable.Interval(TimeSpan.FromSeconds(1))
                .Subscribe(_ =>
                    {
                        var newClient = new JsonRestClientAsync("http://g-un--:1337/");
                        newClient.PutAsync<object>(
                            "/async",
                            new ResourceRequest() { ResourceKey = Guid.NewGuid().ToString() },
                            response =>
                            {
                                Console.WriteLine("Put was sent!");
                            },
                            (response, exception) =>
                            {
                                Console.WriteLine(exception);
                            });
                    });

            Console.ReadLine();
        }
Esempio n. 39
0
        public void complete_is_sent_through_scheduler()
        {
            ManualScheduler scheduler = new ManualScheduler();

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

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

            subject.OnCompleted();

            subject.Subscribe(stats);

            Assert.IsFalse(stats.NextCalled);

            scheduler.RunNext();
            Assert.AreEqual(0, stats.NextCount);
            Assert.IsTrue(stats.CompletedCalled);
        }
Esempio n. 40
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.IsCollection(3333);

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

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

                // re subscription
                onNext.Clear();
                _.Dispose();
                subject.Subscribe(x => onNext.Add(x), x => exception.Add(x), () => onCompletedCallCount++);
                onNext.IsCollection(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.IsCollection(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);
            }
        }
        public void HasObservers_OnError()
        {
            var s = new BehaviorSubject<int>(42);
            Assert.IsFalse(s.HasObservers);

            var d = s.Subscribe(_ => { }, ex => { });
            Assert.IsTrue(s.HasObservers);

            s.OnNext(42);
            Assert.IsTrue(s.HasObservers);

            s.OnError(new Exception());
            Assert.IsFalse(s.HasObservers);
        }
        public void HasObservers_OnCompleted()
        {
            var s = new BehaviorSubject<int>(42);
            Assert.IsFalse(s.HasObservers);

            var d = s.Subscribe(_ => { });
            Assert.IsTrue(s.HasObservers);

            s.OnNext(42);
            Assert.IsTrue(s.HasObservers);

            s.OnCompleted();
            Assert.IsFalse(s.HasObservers);
        }
        public void HasObservers_Dispose2()
        {
            var s = new BehaviorSubject<int>(42);
            Assert.IsFalse(s.HasObservers);

            var d = s.Subscribe(_ => { });
            Assert.IsTrue(s.HasObservers);

            d.Dispose();
            Assert.IsFalse(s.HasObservers);

            s.Dispose();
            Assert.IsFalse(s.HasObservers);
        }
        public void HasObservers()
        {
            var s = new BehaviorSubject<int>(42);
            Assert.IsFalse(s.HasObservers);

            var d1 = s.Subscribe(_ => { });
            Assert.IsTrue(s.HasObservers);

            d1.Dispose();
            Assert.IsFalse(s.HasObservers);

            var d2 = s.Subscribe(_ => { });
            Assert.IsTrue(s.HasObservers);

            var d3 = s.Subscribe(_ => { });
            Assert.IsTrue(s.HasObservers);

            d2.Dispose();
            Assert.IsTrue(s.HasObservers);

            d3.Dispose();
            Assert.IsFalse(s.HasObservers);
        }
Esempio n. 45
0
 public static void BehaviorSubjectExample()
 {
     //Need to provide a default value.
     var subject = new BehaviorSubject<string>("a");
     subject.Subscribe(Console.WriteLine);
 }
Esempio n. 46
0
        public void replays_no_values_when_errored()
        {
            BehaviorSubject<int> subject = new BehaviorSubject<int>(0);

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

            subject.OnNext(1);
            subject.OnNext(2);
            subject.OnNext(3);
            subject.OnError(new Exception());

            subject.Subscribe(stats);

            Assert.AreEqual(0, stats.NextCount);
            Assert.IsTrue(stats.ErrorCalled);
        }
Esempio n. 47
0
        public void only_replays_one_value()
        {
            BehaviorSubject<int> subject = new BehaviorSubject<int>(0);

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

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

            subject.Subscribe(stats);

            Assert.AreEqual(1, stats.NextCount);
            Assert.IsTrue(stats.NextValues.SequenceEqual(new int[] { 2 }));
        }
Esempio n. 48
0
        public void replays_no_values_when_complete()
        {
            BehaviorSubject<int> subject = new BehaviorSubject<int>(0);

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

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

            subject.Subscribe(stats);

            Assert.AreEqual(0, stats.NextCount);
            Assert.IsTrue(stats.CompletedCalled);
        }
Esempio n. 49
0
        public void replays_empty_sequence()
        {
            BehaviorSubject<int> subject = new BehaviorSubject<int>(0);

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

            subject.OnCompleted();

            subject.Subscribe(stats);

            Assert.AreEqual(0, stats.NextCount);
            Assert.IsTrue(stats.CompletedCalled);
        }
Esempio n. 50
0
        public void replays_error_sequence()
        {
            BehaviorSubject<int> subject = new BehaviorSubject<int>(0);

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

            subject.OnError(new Exception());

            subject.Subscribe(stats);

            Assert.IsTrue(stats.ErrorCalled);
        }
Esempio n. 51
0
 static void Example1()
 {
     var subject = new BehaviorSubject<string>("a");
       subject.Subscribe(Console.WriteLine);
 }
Esempio n. 52
0
        public void sends_live_values_after_replay()
        {
            BehaviorSubject<int> subject = new BehaviorSubject<int>(0);

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

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

            subject.Subscribe(stats);

            subject.OnNext(3);
            subject.OnCompleted();

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