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); }
public static void BehaviorSubjectExample3() { var subject = new BehaviorSubject<string>("a"); subject.OnNext("b"); subject.Subscribe(Console.WriteLine); subject.OnNext("c"); subject.OnNext("d"); }
static void Example4() { var subject = new BehaviorSubject<string>("a"); subject.OnNext("b"); subject.OnNext("c"); subject.OnNext("d"); subject.OnCompleted(); subject.Subscribe(Console.WriteLine); }
///<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)); }
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); }
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); }
public async Task Observable_Current_returns_latest_element() { var subject = new BehaviorSubject<int>(1); var asyncEnumerable = subject.Current(); using (var asyncEnumerator = asyncEnumerable.GetEnumerator()) { subject.OnNext(2); subject.OnNext(3); subject.OnNext(4); Assert.True(await asyncEnumerator.MoveNext(CancellationToken.None)); Assert.Equal(4, asyncEnumerator.Current); } }
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)); }
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(); } }
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(); }); }
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; }); }
/// <summary> /// Starts the search. Pushes whenever the solver finds a solution. /// Cannot expost IObservable because it conflicts with FSharp.Core which contains the same type, /// this conflict is why FoundOPS.SLClient.Algorithm is a seperate project. /// </summary> /// <param name="locationsToRoute">The locations to route</param> public BehaviorSubject<SolutionMessage<IList<IGeoLocation>>> Search(IList<IGeoLocation> locationsToRoute) { var foundSolution = new BehaviorSubject<SolutionMessage<IList<IGeoLocation>>>(null); _solver.FoundSolution += (s, e) => foundSolution.OnNext(e); var generator = new Func<Random, IList<IGeoLocation>>(random => Tsp.Shuffle(random, locationsToRoute)); var mutator = new Func<IList<IGeoLocation>, Random, IList<IGeoLocation>>((solution, random) => Tsp.Swap(random, solution)); var evaluator = new Func<IList<IGeoLocation>, double>(circuit => -Tsp.Length(circuit)); var problem = new Problem<IList<IGeoLocation>>(generator, mutator, evaluator); _solver.Search(problem); return foundSolution; }
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); }
public void InitializesCanExecuteValueSourceAndSyncExecuteAction( object parameter) { var canExecuteSource = new BehaviorSubject<bool>(true); var functor = Mock.Of<IFunctor>(); var command = ReactiveCommand.Create( canExecuteSource, p => functor.Action(p)); command?.Execute(parameter); canExecuteSource.OnNext(false); command.Should().NotBeNull(); command.CanExecute(parameter).Should().BeFalse(); Mock.Get(functor).Verify(f => f.Action(parameter), Times.Once()); }
public void Produces_a_value_each_time_the_aggregate_availability_of_dependencies_changes() { var dependency = new BehaviorSubject<bool>(false); var activator = new FeatureActivator(() => { }, dependsOn: dependency); var notifications = new List<bool>(); disposables.Add(activator.Subscribe(notifications.Add)); dependency.OnNext(false); dependency.OnNext(false); dependency.OnNext(true); dependency.OnNext(true); dependency.OnNext(true); dependency.OnNext(true); dependency.OnNext(false); dependency.OnNext(false); dependency.OnNext(false); Assert.That(notifications.IsSameSequenceAs(false, true, false)); }
public void Should_Get_Simple_Observable_Value() { using (var sync = UnitTestSynchronizationContext.Begin()) { var source = new BehaviorSubject<string>("foo"); var data = new { Foo = source }; var target = new ExpressionObserver(data, "Foo"); var result = new List<object>(); var sub = target.Subscribe(x => result.Add(x)); source.OnNext("bar"); sync.ExecutePostedCallbacks(); Assert.Equal(new[] { PerspexProperty.UnsetValue, "foo", "bar" }, result); } }
public void Should_Not_Get_Observable_Value_Without_Modifier_Char() { using (var sync = UnitTestSynchronizationContext.Begin()) { var source = new BehaviorSubject<string>("foo"); var data = new { Foo = source }; var target = new ExpressionObserver(data, "Foo"); var result = new List<object>(); var sub = target.Subscribe(x => result.Add(x)); source.OnNext("bar"); sync.ExecutePostedCallbacks(); Assert.Equal(new[] { source }, result); } }
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(); }
public void Should_Get_Simple_Observable_Value_With_DataValidation_Enabled() { using (var sync = UnitTestSynchronizationContext.Begin()) { var source = new BehaviorSubject<string>("foo"); var data = new { Foo = source }; var target = new ExpressionObserver(data, "Foo^", true); var result = new List<object>(); var sub = target.Subscribe(x => result.Add(x)); source.OnNext("bar"); sync.ExecutePostedCallbacks(); // What does it mean to have data validation on an observable? Without a use-case // it's hard to know what to do here so for the moment the value is returned. Assert.Equal(new[] { "foo", "bar" }, result); } }
private async Task signup() { var shakeTargets = ShakeTargets.None; if (!emailSubject.Value.IsValid) { shakeTargets |= ShakeTargets.Email; } if (!passwordSubject.Value.IsValid) { shakeTargets |= ShakeTargets.Password; } if (!countryId.HasValue) { shakeTargets |= ShakeTargets.Country; } if (shakeTargets != ShakeTargets.None) { shakeSubject.OnNext(shakeTargets); return; } await requestAcceptanceOfTermsAndConditionsIfNeeded(); if (!termsOfServiceAccepted || isLoadingSubject.Value) { return; } isLoadingSubject.OnNext(true); errorMessageSubject.OnNext(string.Empty); var supportedTimezonesObs = new GetSupportedTimezonesInteractor(new JsonSerializer()).Execute(); signupDisposable = supportedTimezonesObs .Select(supportedTimezones => supportedTimezones.FirstOrDefault(tz => platformInfo.TimezoneIdentifier == tz)) .SelectMany(timezone => userAccessManager .SignUp( emailSubject.Value, passwordSubject.Value, termsOfServiceAccepted, (int)countryId.Value, timezone) ) .Track(analyticsService.SignUp, AuthenticationMethod.EmailAndPassword) .Subscribe(onInteractorFactory, onError, onCompleted); }
public void AvailableNetworkStartsSongSearch() { var isAvailable = new BehaviorSubject<bool>(false); var networkStatus = Substitute.For<INetworkStatus>(); networkStatus.IsAvailable.Returns(isAvailable); var songFinder = Substitute.For<IYoutubeSongFinder>(); songFinder.GetSongsAsync(Arg.Any<string>()) .Returns(Task.FromResult((IReadOnlyList<YoutubeSong>)new List<YoutubeSong>())); using (var library = Helpers.CreateLibrary()) { Guid token = library.LocalAccessControl.RegisterLocalAccessToken(); var vm = new YoutubeViewModel(library, new ViewSettings(), new CoreSettings(), token, networkStatus, songFinder); isAvailable.OnNext(true); songFinder.ReceivedWithAnyArgs(1).GetSongsAsync(null); } }
public void Should_Get_Simple_Observable_Value_With_DataValidation_Enabled() { using (var sync = UnitTestSynchronizationContext.Begin()) { var source = new BehaviorSubject <string>("foo"); var data = new { Foo = source }; var target = ExpressionObserver.Create(data, o => o.Foo.StreamBinding(), true); var result = new List <object>(); var sub = target.Subscribe(x => result.Add(x)); source.OnNext("bar"); sync.ExecutePostedCallbacks(); // What does it mean to have data validation on an observable? Without a use-case // it's hard to know what to do here so for the moment the value is returned. Assert.Equal(new[] { "foo", "bar" }, result); GC.KeepAlive(data); } }
/// <summary> /// Adds to stack and tick. /// </summary> /// <typeparam name="T">The view model type.</typeparam> /// <param name="stackSubject">The stack subject.</param> /// <param name="item">The item.</param> /// <param name="reset">if set to <c>true</c> [reset].</param> protected static void AddToStackAndTick <T>(BehaviorSubject <IImmutableList <T> > stackSubject, T item, bool reset) { if (stackSubject is null) { throw new ArgumentNullException(nameof(stackSubject)); } var stack = stackSubject.Value; if (reset) { stack = new[] { item }.ToImmutableList(); } else { stack = stack.Add(item); } stackSubject.OnNext(stack); }
/// <summary> /// Pops the stack and notifies observers. /// </summary> /// <typeparam name="T">The view model type.</typeparam> /// <param name="stackSubject">The stack subject.</param> /// <returns>The view model popped.</returns> /// <exception cref="InvalidOperationException">Stack is empty.</exception> protected static T PopStackAndTick <T>(BehaviorSubject <IImmutableList <T> > stackSubject) { if (stackSubject is null) { throw new ArgumentNullException(nameof(stackSubject)); } var stack = stackSubject.Value; if (stack.Count == 0) { throw new InvalidOperationException("Stack is empty."); } var removedItem = stack[stack.Count - 1]; stack = stack.RemoveAt(stack.Count - 1); stackSubject.OnNext(stack); return(removedItem); }
/// <summary> /// Constructor /// </summary> public App() { InitializeComponent(); // Apply styles. if (Resources == null) { Resources = new ResourceDictionary(); } FeedCardStyling.Apply(Resources); // Open and initialize storage. var tuple = StorageFactory.OpenStorage(StorageFileName, 1, CancellationToken.None); if (tuple.Item2 != null) { tuple.Item2.StartInitializationAsync(CancellationToken.None); tuple.Item2.CompleteInitialization(); } // Subscribe for connectivity changing events. _isConnectivityAvailable = new BehaviorSubject <bool>(CrossConnectivity.Current.IsConnected); CrossConnectivity.Current.ConnectivityChanged += (sender, args) => { _isConnectivityAvailable.OnNext(args.IsConnected); }; var reactiveData = new ReactiveData(tuple.Item1); var feedProvider = new FeedProvider(new RssParser(new HtmlToTextConverter()), tuple.Item1); _actionService = new ActionService(reactiveData, tuple.Item1, feedProvider, _isConnectivityAvailable, OpenDetailPage, ShowConnectivityErrorDialog); var mainPage = new HomePage(new HomePageViewModel(_actionService, reactiveData.FeedListObservable)); // Set main page. MainPage = new NavigationPage(mainPage); }
private IObservable <int> TransferFileAsync(SongTransferMessage message) { const int bufferSize = 32 * 1024; int written = 0; Stream stream = this.currentFileTransferClient.GetStream(); var progress = new BehaviorSubject <int>(0); Task.Run(async() => { this.Log().Info("Starting a file transfer with ID: {0} and a size of {1} bytes", message.TransferId, message.Data.Length); var traits = new Dictionary <string, string> { { "Size", message.Data.Length.ToString() } }; using (Insights.TrackTime("Song Transfer", traits)) { byte[] data = await NetworkHelpers.PackFileTransferMessageAsync(message); using (var dataStream = new MemoryStream(data)) { var buffer = new byte[bufferSize]; int count; while ((count = dataStream.Read(buffer, 0, bufferSize)) > 0) { stream.Write(buffer, 0, count); written += count; progress.OnNext((int)(100 * ((double)written / data.Length))); } } } progress.OnCompleted(); }); return(progress.DistinctUntilChanged()); }
public Hangman(string word) { var emptySetOfChars = new HashSet <char>(); var maskedWord = MaskedWord(word, emptySetOfChars); var hangmanState = new HangmanState(maskedWord, emptySetOfChars.ToImmutableHashSet(), MaxGuessCount); var stateSubject = new BehaviorSubject <HangmanState>(hangmanState); StateObservable = stateSubject; GuessObserver = Observer.Create <char>(@char => { var guessedChars = new HashSet <char>(stateSubject.Value.GuessedChars); var isHit = !guessedChars.Contains(@char) && word.Contains(@char); guessedChars.Add(@char); var maskedWord = MaskedWord(word, guessedChars); if (maskedWord == word) { stateSubject.OnCompleted(); } else if (stateSubject.Value.RemainingGuesses < 1) { stateSubject.OnError(new TooManyGuessesException()); } else { var guessCount = isHit ? stateSubject.Value.RemainingGuesses : stateSubject.Value.RemainingGuesses - 1; var hangmanState = new HangmanState(maskedWord, guessedChars.ToImmutableHashSet(), guessCount); stateSubject.OnNext(hangmanState); } }); }
public void TestMethod1() { var s0 = new BehaviorSubject <bool>(false); var s1 = new BehaviorSubject <bool>(false); bool l = false; var c = new BoolObservableConcetrator(); var r0 = c.RegisterSource(s0); var r1 = c.RegisterSource(s1); var s = c.Subscribe(v => l = v); Assert.AreEqual(false, l); s0.OnNext(true); Assert.AreEqual(false, l); s1.OnNext(true); Assert.AreEqual(true, l); s0.OnNext(false); Assert.AreEqual(false, l); // Removing one of the message sources should update the result r0.Dispose(); Assert.AreEqual(true, l); }
public void CommandBindSetsDisablesCommandWhenCanExecuteChanged() { var vm = new CommandBindViewModel(); var view = new CommandBindView() { ViewModel = vm }; var canExecute1 = new BehaviorSubject <bool>(true); var cmd1 = ReactiveCommand.Create(() => { }, canExecute1); vm.Command1 = cmd1; var disp = view.BindCommand(vm, x => x.Command1, x => x.Command1); Assert.True(view.Command1.IsEnabled); canExecute1.OnNext(false); Assert.False(view.Command1.IsEnabled); }
public void Stream_Binding_To_Observable_Works() { using (UnitTestApplication.Start(TestServices.MockWindowingPlatform)) { var xaml = @" <Window xmlns='https://github.com/avaloniaui' xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml'> <TextBlock Name='textblock' Text='{Binding Observable^}'/> </Window>"; var window = (Window)AvaloniaRuntimeXamlLoader.Load(xaml); var textBlock = (TextBlock)window.Content; var observable = new BehaviorSubject <string>("foo"); window.DataContext = new { Observable = observable }; window.ApplyTemplate(); Assert.Equal("foo", textBlock.Text); observable.OnNext("bar"); Assert.Equal("bar", textBlock.Text); } }
public object BehaviorSubjectPush() { var subj = new BehaviorSubject <int>(-1); var consumers = new IDisposable[M]; var m = M; for (var i = 0; i < m; i++) { consumers[i] = subj.Subscribe(v => Volatile.Write(ref _store, v)); } var n = N; for (var i = 0; i < n; i++) { subj.OnNext(i); } subj.OnCompleted(); return(consumers); }
public void Does_Not_Call_Converter_ConvertBack_On_OneWay_Binding() { var control = new Decorator { Name = "foo" }; var style = Mock.Of <IStyle>(); var binding = new Binding("Name", BindingMode.OneWay) { Converter = new TestConverter(), RelativeSource = new RelativeSource(RelativeSourceMode.Self), }; var setter = new Setter(Decorator.TagProperty, binding); var activator = new BehaviorSubject <bool>(true); setter.Apply(style, control, activator); Assert.Equal("foobar", control.Tag); // Issue #1218 caused TestConverter.ConvertBack to throw here. activator.OnNext(false); Assert.Null(control.Tag); }
public async Task ReferenceDriveAsync() { _currentStatus.OnNext(Status.NotReady); var referenceSpeedInStepsPerSecond = DriveSetting.ReferenceDrivingSpeed.ToStepsPerSecond(DriveSetting); var waitTimeBetweenSteps = new Duration(1 / referenceSpeedInStepsPerSecond / 2.0, DurationUnit.Second); var direction = GetReferenceDirection(); _drivingTask = Task.Run(() => { ReferenceDrive(waitTimeBetweenSteps, direction); }); await _drivingTask; _drivingTask = Task.CompletedTask; }
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 void PublishPositionReport() { var pud = new PositionUpdatesDto { CurrentPositions = _ccyPairTracker .Values .Where(ccp => ccp.TradeCount > 0) .Select(ccp => new CurrencyPairPositionDto { Symbol = ccp.CurrencyPair, BasePnl = ccp.CurrentPosition.BasePnl, BaseTradedAmount = ccp.CurrentPosition.BaseTradedAmount, CounterTradedAmount = ccp.CurrentPosition.CounterTradedAmount, }) .ToArray() }; var usdPnl = _ccyPairTracker.Values .Where(ccp => ccp.TradeCount > 0) .Sum(ccp => ccp.CurrentPosition.UsdPnl); var now = DateTimeOffset.UtcNow; var window = now.AddMinutes(-15); pud.History = _currentPositionUpdatesDto.History .Where(hpu => hpu.Timestamp >= window) .Concat(new[] { new HistoricPositionDto { Timestamp = now, UsdPnl = usdPnl } }) .ToArray(); lock (_currentPositionLock) { _currentPositionUpdatesDto = pud; } Log.Information(pud.ToString()); _updates.OnNext(pud); }
public Hangman(string word) { var emptySet = new HashSet <char>(); var subject = new BehaviorSubject <HangmanState>(new HangmanState( Mask(word, emptySet), emptySet.ToImmutableHashSet(), MaxGuesses )); this.StateObservable = subject; this.GuessObserver = Observer.Create <char>(ch => { var guessedChars = new HashSet <char>(subject.Value.GuessedChars); var remainingGuesses = subject.Value.RemainingGuesses; if (!word.Contains(ch) || guessedChars.Contains(ch)) { remainingGuesses--; } guessedChars.Add(ch); var masked = Mask(word, guessedChars); if (masked == word) { subject.OnCompleted(); } else if (remainingGuesses < 0) // Game over { subject.OnError(new TooManyGuessesException()); } else { subject.OnNext(new HangmanState( masked, guessedChars.ToImmutableHashSet(), remainingGuesses )); } } ); }
public async Task Observable_Current_returns_elements_repeatedly() { var subject = new BehaviorSubject <int>(1); var asyncEnumerable = subject.Current(); await using (var asyncEnumerator = asyncEnumerable.GetAsyncEnumerator()) { for (var i = 0; i < 10; i++) { Assert.True(await asyncEnumerator.MoveNextAsync()); Assert.Equal(1, asyncEnumerator.Current); } subject.OnNext(2); for (var i = 0; i < 10; i++) { Assert.True(await asyncEnumerator.MoveNextAsync()); Assert.Equal(2, asyncEnumerator.Current); } } }
public void When_any_dependency_produces_false_then_deactivate_is_called() { var deactivations = 0; var dependency1 = new BehaviorSubject <bool>(true); var dependency2 = new BehaviorSubject <bool>(true); var activator = new FeatureActivator( activate: () => { }, deactivate: () => deactivations++, dependsOn: new[] { dependency1, dependency2 }); var notifications = new List <bool>(); disposables.Add(activator.Subscribe(notifications.Add)); Assert.That(deactivations, Is.EqualTo(0)); Assert.That(notifications.IsSameSequenceAs(true)); dependency1.OnNext(false); Assert.That(deactivations, Is.EqualTo(1)); Assert.That(notifications.IsSameSequenceAs(true, false)); }
public void SortAfterFilterList() { var source = new SourceList <Person>(); var filterSubject = new BehaviorSubject <Func <Person, bool> >(p => true); var agg = source.Connect() .Filter(filterSubject) .Transform(x => new ViewModel(x.Name)) .Sort(new ViewModel.Comparer()) .AsAggregator(); source.Edit(x => { x.Add(new Person("A", 1, "F")); x.Add(new Person("a", 1, "M")); x.Add(new Person("B", 1, "F")); x.Add(new Person("b", 1, "M")); }); filterSubject.OnNext(p => p.Name.Equals("a", StringComparison.InvariantCultureIgnoreCase)); }
public static void Create() { var lightTheme = new OriginalLightTheme(); var darkTheme = new OriginalDarkTheme(); var path = new BehaviorSubject <string>(string.Empty); var refresh = new BehaviorSubject <Unit>(Unit.Default); var image = path .CombineLatest(refresh, ((p, _) => p)) .Select(p => AbsoluteFilePath.TryParse(p) .Where(f => File.Exists(f.NativePath)) .Select( absPath => absPath.NativePath.EndsWith(".svg") ? (IImage) new SvgImage(() => File.OpenRead(absPath.NativePath)) : new MultiResolutionImage( new[] { new ImageStream(new Ratio <Pixels, Points>(1), () => File.OpenRead(absPath.NativePath)) })) .Or(() => (IImage) new SvgImage(() => new MemoryStream(FallbackImage)))); var content = Layout.Dock().Top( Layout.Dock() .Left(Label.Create("Path: ", font: Theme.DefaultFont, color: Theme.DefaultText).CenterVertically()) .Right(Buttons.DefaultButton("Refresh", Command.Enabled(() => refresh.OnNext(Unit.Default)))) .Fill(ThemedTextBox.Create(path.AsProperty()))) .Fill(Layout.SubdivideHorizontally(ImageVersionsRowForTheme(image, darkTheme), ImageVersionsRowForTheme(image, lightTheme))) .WithBackground(Theme.PanelBackground); Application.Desktop.CreateSingletonWindow( Observable.Return(true), dialog => new Window { Title = Observable.Return("Icon preview"), Size = Property.Create <Optional <Size <Points> > >(new Size <Points>(600, 600)).ToOptional(), Content = content, Background = Theme.PanelBackground, Foreground = Theme.DefaultText, Border = Separator.MediumStroke }); }
public JsonWatcher() { _rootSubject = new BehaviorSubject <JObject>(null); FileSystemWatcher watcher = new FileSystemWatcher(PathUtil.ObtainStoragePath(), "*.json") { NotifyFilter = NotifyFilters.LastWrite }; ObserveRootLoad() .Concat( Observable .FromEventPattern <FileSystemEventArgs>(watcher, nameof(watcher.Changed)) .Select(pattern => pattern.EventArgs) .Where(fileArgs => fileArgs.FullPath == PathUtil.ObtainStorageFilePath()) .Delay(TimeSpan.FromSeconds(5)) .SwitchSelect(_ => ObserveRootLoad()) ) .Subscribe(root => _rootSubject.OnNext(root)); watcher.EnableRaisingEvents = true; }
public static IObservable <TOut> Drain <TSource, TOut>(this IObservable <TSource> source, Func <TSource, IObservable <TOut> > selector) { return(Observable.Defer(() => { BehaviorSubject <Unit> queue = new BehaviorSubject <Unit>(new Unit()); var stack = new Stack <TSource>(); return source .Do(item => stack.Push(item)) .Zip(queue, (v, q) => v) .Select(_ => stack.Pop()) .SelectMany(v => selector(v) .Do(_ => { }, () => { queue.OnNext(new Unit()); }) ); })); }
public void SortAfterFilter() { var source = new SourceCache <Person, string>(p => p.Key); var filterSubject = new BehaviorSubject <Func <Person, bool> >(p => true); var agg = new SortedChangeSetAggregator <ViewModel, TestString>(source.Connect() .Filter(filterSubject) .Group(x => (TestString)x.Key) .Transform(x => new ViewModel(x.Key)) .Sort(new ViewModel.Comparer())); source.Edit(x => { x.AddOrUpdate(new Person("A", 1, "F")); x.AddOrUpdate(new Person("a", 1, "M")); x.AddOrUpdate(new Person("B", 1, "F")); x.AddOrUpdate(new Person("b", 1, "M")); }); filterSubject.OnNext(p => p.Name.Equals("a", StringComparison.InvariantCultureIgnoreCase)); }
void CreateObservables() { // trigger an observable based on when the player's position changes playerLocation = new BehaviorSubject <Vector2>(Vector2.zero); latitude.Merge(longitude) .Select((float _) => { // value could be either lat or lng, so just cheat and grab the current property values return(new Vector2(longitude.Value, latitude.Value)); }) .Subscribe((Vector2 coords) => { playerLocation.OnNext(coords); }); activeStar = new BehaviorSubject <StarController>(null); deliveryDestinations = new BehaviorSubject <Dictionary <int, int> >(GenerateDeliveries()); fuelAvailable .Select((x) => x < 3 && fuelTimeRemaining.Value == 0) .Subscribe((x) => { StartFuelTimer(); }); }
public async Task DynamicNumThreads_IncreasedWhileWorking() { var subj = new BehaviorSubject <int>(Small); var tcs = new TaskCompletionSource <bool>(); using (var queue = new WorkQueue(subj)) { Assert.Equal(Small, queue.DesiredNumWorkers); Assert.Equal(Small, queue._tasks.Count); Enumerable.Range(0, Small).Do(_ => queue.QueueTask(() => tcs.Task)); subj.OnNext(Large); Assert.Equal(Large, queue.DesiredNumWorkers); Assert.Equal(Large, queue._tasks.Count); Task.Run(() => tcs.SetResult(true)).FireAndForget(); Assert.Equal(Large, queue.DesiredNumWorkers); Assert.Equal(Large, queue._tasks.Count); await Task.Delay(PollMS * 2); Assert.Equal(Large, queue.DesiredNumWorkers); Assert.Equal(Large, queue._tasks.Count); } }
private async Task OnDeviceModeChanged() { if (ConnectedDevice.IsModeRtsp) { _viewMode.OnNext(ConnectedDevice.IsPreviewOutput ? ViewMode.Output : ViewMode.Input); if (ConnectedDevice.IsConnected && VideoPlayer.IsEnabled && !VideoPlayer.IsPlaying) { await VideoPlayer.PlayVideo(ConnectedDevice.PreviewUri); } } else { await VideoPlayer.StopVideo(); _viewMode.OnNext(ConnectedDevice.IsModeRecording ? ViewMode.Rec : ViewMode.Live); } }
public static DockBuilder Panel( this DockBuilder dock, RectangleEdge dockEdge, IProperty <Points> size, IObservable <bool> isExpanded, IControl control, Points minSize, bool resizable = true) { var availableSize = new BehaviorSubject <Size <IObservable <Points> > >( new Size <IObservable <Points> >(Observable.Return <Points>(double.MaxValue), Observable.Return <Points>(double.MaxValue))); var maxWidth = availableSize.Switch()[dockEdge.NormalAxis()]; control = control .WithBackground(Theme.PanelBackground) .WithFrame(f => f, a => a.WithAxis(dockEdge.NormalAxis(), s => size.Min(maxWidth))) .WithDimension(dockEdge.NormalAxis(), size.Min(maxWidth)); control = Layout.Dock() .Dock(edge: dockEdge, control: control) .Dock(edge: dockEdge, control: Separator.Medium) .Fill(); if (resizable) { control = control.MakeResizable(dockEdge.Opposite(), size, minSize: minSize); } control = control.MakeCollapsable(dockEdge.Opposite(), isExpanded, lazy: false); control = control.WithFrame( frame => frame, availSize => { availableSize.OnNext(availSize); return(availSize); }); return(dock.Dock(edge: dockEdge, control: control)); }
public About(Version version, Debug debug) { var showAboutDialog = new BehaviorSubject <bool>(false); var thanksTo = "Created by:\n\n" + "João Abecasis, Karina Asaevich, Christopher Bagley, Alexander Bladyko, Anders Bondehagen, Aaron Cohen, Liam Crouch, " + "Håkon Martin Eide, Guro Faller, Erik Faye-Lund, Morten Daniel Fornes, Olle Fredriksson, Anette Gjetnes, Lorents Odin Gravås, " + "Kristian Hasselknippe, Daniel Hollick, Erik Hvattum, Anders Schau Knatten, Anders Knive Lassen, Vegard Lende, Vika Lepeshinskaya, " + "Sumi Lim, edA-qa mort-ora-y, Trond Arve Nordheim, Remi Johan Pedersen, Evgeny Razumov, Jonny Ree, Sebastian Reinhard, " + "Jan Stefan Rimaila, Andreas Rønning, Emil Sandstø, Bent Stamnes, Karsten Nikolai Strand, Jake Taylor." + "\n\n Fuse © 2017"; Application.Desktop.CreateSingletonWindow( isVisible: showAboutDialog, window: dialog => new Window { Title = Observable.Return("About Fuse"), Content = Control.Lazy(() => Layout.Dock() .Top(LogoAndVersion.Create(version).WithMacWindowStyleCompensation()) .Bottom(CreateOkButton(Command.Enabled(() => dialog.Close()))) .Bottom(Separator.Medium) .Fill( Label.Create(font: Theme.DefaultFont, color: Theme.DefaultText, lineBreakMode: LineBreakMode.Wrap, text: thanksTo) .OnMouse(debug.EnableDebugMenuByRapidClicking) .WithPadding(Thickness.Create(new Points(20), 10, 20, 10)) ).WithBackground(Theme.PanelBackground)), Size = Optional.Some(Property.Constant(Optional.Some(new Size <Points>(370, 520)))), Background = Theme.PanelBackground, Foreground = Theme.DefaultText, Border = Separator.MediumStroke, Style = WindowStyle.Fat } ); Menu = Menu.Item("About Fuse", () => showAboutDialog.OnNext(true)); }
public Build(IProject project, ProjectPreview preview, PreviewOnDevice previewOnDevice, Command enableUsbMode, BuildArgs args) { var buildLibraries = new BehaviorSubject <bool>(false); var rebuilt = new Subject <object>(); Rebuilt = rebuilt; Rebuild = Command.Enabled(() => { rebuilt.OnNext(new object()); preview.Rebuild(); }); Refresh = Command.Enabled(preview.Refresh); var buildFlagsWindowVisible = new BehaviorSubject <bool>(false); BuildFlags = Command.Enabled(() => buildFlagsWindowVisible.OnNext(true)); Application.Desktop.CreateSingletonWindow( isVisible: buildFlagsWindowVisible, window: window => BuildFlagsWindow.Create(buildFlagsWindowVisible, args)); BuildArguments = Observable.CombineLatest( args.Defines, buildLibraries, args.Verbose, project.FilePath, (d, bl, vb, pp) => new BuildProject(pp.NativePath, List.Create(d.ToArray()), bl, vb)); Menu = Menu.Item("Refresh", Refresh, hotkey: HotKey.Create(ModifierKeys.Meta, Key.R)) + Menu.Item("Rebuild", Rebuild, hotkey: HotKey.Create(ModifierKeys.Meta | ModifierKeys.Shift, Key.R)) + Menu.Separator + Menu.Item("Reconnect USB (Android)", enableUsbMode) + Menu.Separator + previewOnDevice.Menu + Menu.Separator + Menu.Item("Build flags", BuildFlags); }
/// <summary> /// For DetailsRow /// </summary> /// <param name="item"></param> /// <param name="asSingle">On click, force list to select one even if set to multiple</param> public void SelectItem(TItem item, bool asSingle = false) { bool hasChanged = false; if (SelectionMode == SelectionMode.Multiple && !asSingle) { hasChanged = true; if (selectedItems.Contains(item)) { selectedItems.Remove(item); } else { selectedItems.Add(item); } } else if (SelectionMode == SelectionMode.Multiple && asSingle) { //same as single except we need to clear other items if they are selected, too hasChanged = true; selectedItems.Clear(); selectedItems.Add(item); } else if (SelectionMode == SelectionMode.Single) { if (!selectedItems.Contains(item)) { hasChanged = true; selectedItems.Clear(); selectedItems.Add(item); } } if (hasChanged) { doNotRenderOnce = true; selectedItemsSubject.OnNext(selectedItems); SelectionChanged.InvokeAsync(new Selection <TItem>(selectedItems)); } }
public async Task Observable_Current_completes_on_source_completion() { var subject = new BehaviorSubject<int>(1); var asyncEnumerable = subject.Current(); using (var asyncEnumerator = asyncEnumerable.GetEnumerator()) { subject.OnNext(1); subject.OnNext(2); subject.OnNext(3); subject.OnCompleted(); Assert.False(await asyncEnumerator.MoveNext(CancellationToken.None)); } }
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 Value_FrozenAfterOnCompleted() { var s = new BehaviorSubject<int>(42); Assert.AreEqual(42, s.Value); s.OnNext(43); Assert.AreEqual(43, s.Value); s.OnNext(44); Assert.AreEqual(44, s.Value); s.OnCompleted(); Assert.AreEqual(44, s.Value); s.OnNext(1234); Assert.AreEqual(44, s.Value); }
public void Value_Second() { var s = new BehaviorSubject<int>(42); Assert.AreEqual(42, s.Value); s.OnNext(43); Assert.AreEqual(43, s.Value); s.OnNext(44); Assert.AreEqual(44, s.Value); }
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 Value_FrozenAfterOnCompleted() { var s = new BehaviorSubject<int>(42); Assert.AreEqual(42, s.Value); var x = default(int); Assert.IsTrue(s.TryGetValue(out x)); Assert.AreEqual(42, x); s.OnNext(43); Assert.AreEqual(43, s.Value); Assert.IsTrue(s.TryGetValue(out x)); Assert.AreEqual(43, x); s.OnNext(44); Assert.AreEqual(44, s.Value); Assert.IsTrue(s.TryGetValue(out x)); Assert.AreEqual(44, x); s.OnCompleted(); Assert.AreEqual(44, s.Value); Assert.IsTrue(s.TryGetValue(out x)); Assert.AreEqual(44, x); s.OnNext(1234); Assert.AreEqual(44, s.Value); Assert.IsTrue(s.TryGetValue(out x)); Assert.AreEqual(44, x); }
public void Style_With_ObservableSetter_Should_Update_And_Restore_Value() { var source = new BehaviorSubject<string>("Foo"); Style style = new Style(x => x.OfType<Class1>().Class("foo")) { Setters = new[] { new ObservableSetter(Class1.FooProperty, source), }, }; var target = new Class1(); style.Attach(target); Assert.Equal("foodefault", target.Foo); target.Classes.Add("foo"); Assert.Equal("Foo", target.Foo); source.OnNext("Bar"); Assert.Equal("Bar", target.Foo); target.Classes.Remove("foo"); Assert.Equal("foodefault", target.Foo); }
public async Task Observable_Current_propagates_exception() { var subject = new BehaviorSubject<int>(1); var asyncEnumerable = subject.Current(); using (var asyncEnumerator = asyncEnumerable.GetEnumerator()) { subject.OnNext(1); subject.OnNext(2); subject.OnNext(3); subject.OnError(new InvalidOperationException()); asyncEnumerator .Awaiting(_ => _.MoveNext(CancellationToken.None)) .ShouldThrowExactly<AggregateException>() .Where(ex => ex.GetBaseException() is InvalidOperationException); } }
public async Task Observable_Current_returns_elements_repeatedly() { var subject = new BehaviorSubject<int>(1); var asyncEnumerable = subject.Current(); using (var asyncEnumerator = asyncEnumerable.GetEnumerator()) { for (var i = 0; i < 10; i++) { Assert.True(await asyncEnumerator.MoveNext(CancellationToken.None)); Assert.Equal(1, asyncEnumerator.Current); } subject.OnNext(2); for (var i = 0; i < 10; i++) { Assert.True(await asyncEnumerator.MoveNext(CancellationToken.None)); Assert.Equal(2, asyncEnumerator.Current); } } }