public void WithSubscribe() { var testScheduler = new TestScheduler(); var recorder1 = testScheduler.CreateObserver <string>(); var recorder2 = testScheduler.CreateObserver <string>(); var recorder3 = testScheduler.CreateObserver <string>(); var disposable1 = new CompositeDisposable(); var disposable2 = new CompositeDisposable(); var cmd = new ReactiveCommand() .WithSubscribe(() => recorder1.OnNext("x"), disposable1.Add) .WithSubscribe(() => recorder2.OnNext("x"), disposable2.Add) .WithSubscribe(() => recorder3.OnNext("x")); cmd.Execute(); testScheduler.AdvanceBy(10); disposable1.Dispose(); cmd.Execute(); testScheduler.AdvanceBy(10); disposable2.Dispose(); cmd.Execute(); recorder1.Messages.Is( OnNext(0, "x")); recorder2.Messages.Is( OnNext(0, "x"), OnNext(10, "x")); recorder3.Messages.Is( OnNext(0, "x"), OnNext(10, "x"), OnNext(20, "x")); }
public void ReactiveCommandSubscribe() { var testScheduler = new TestScheduler(); var recorder1 = testScheduler.CreateObserver <int>(); var recorder2 = testScheduler.CreateObserver <int>(); var cmd = new ReactiveCommand(); int counter = 0; Action countUp = () => counter++; cmd.Subscribe(countUp); Action recordAction1 = () => recorder1.OnNext(counter); cmd.Subscribe(recordAction1); Action recordAction2 = () => recorder2.OnNext(counter); cmd.Subscribe(recordAction2); cmd.Execute(); testScheduler.AdvanceBy(10); cmd.Execute(); testScheduler.AdvanceBy(10); cmd.Execute(); testScheduler.AdvanceBy(10); recorder1.Messages.Is( OnNext(0, 1), OnNext(10, 2), OnNext(20, 3)); recorder2.Messages.Is( OnNext(0, 1), OnNext(10, 2), OnNext(20, 3)); }
private void Start() { var where = new Subject <bool>(); var rxComm = new ReactiveCommand <string>(where, false); rxComm.Subscribe( value => Debug.LogFormat("Next: {0}", value), ex => Debug.LogException(ex), () => Debug.LogFormat("Complete")); var execute = rxComm.CanExecute; var result = rxComm.Execute("hello rx command."); Debug.LogFormat("CanExecute: {0}, Execute: {1}", execute, result); where.OnNext(true); execute = rxComm.CanExecute; result = rxComm.Execute("hello rx command."); Debug.LogFormat("CanExecute: {0}, Execute: {1}", execute, result); where.OnNext(false); execute = rxComm.CanExecute; result = rxComm.Execute("hello rx command."); Debug.LogFormat("CanExecute: {0}, Execute: {1}", execute, result); }
public void ExecuteFacilitatesAnyNumberOfInFlightExecutions() { new TestScheduler().With( scheduler => { IObservable <Unit> execute = Observables.Unit.Delay(TimeSpan.FromMilliseconds(500), scheduler); ReactiveCommand <Unit, Unit> fixture = ReactiveCommand.CreateFromObservable(() => execute, outputScheduler: scheduler); fixture.ToObservableChangeSet(ImmediateScheduler.Instance).Bind(out ReadOnlyObservableCollection <Unit> executed).Subscribe(); IDisposable sub1 = fixture.Execute().Subscribe(); IDisposable sub2 = fixture.Execute().Subscribe(); scheduler.AdvanceByMs(100); IDisposable sub3 = fixture.Execute().Subscribe(); scheduler.AdvanceByMs(200); IDisposable sub4 = fixture.Execute().Subscribe(); scheduler.AdvanceByMs(100); Assert.True(fixture.IsExecuting.FirstAsync().Wait()); Assert.Empty(executed); scheduler.AdvanceByMs(101); Assert.Equal(2, executed.Count); Assert.True(fixture.IsExecuting.FirstAsync().Wait()); scheduler.AdvanceByMs(200); Assert.Equal(3, executed.Count); Assert.True(fixture.IsExecuting.FirstAsync().Wait()); scheduler.AdvanceByMs(100); Assert.Equal(4, executed.Count); Assert.False(fixture.IsExecuting.FirstAsync().Wait()); }); }
public void WithSubscribeDisposableOverrideGenericVersion() { var testScheduler = new TestScheduler(); var recorder1 = testScheduler.CreateObserver <string>(); var recorder2 = testScheduler.CreateObserver <string>(); var recorder3 = testScheduler.CreateObserver <string>(); var cmd = new ReactiveCommand <string>() .WithSubscribe(x => recorder1.OnNext(x), out var disposable1) .WithSubscribe(x => recorder2.OnNext(x), out var disposable2) .WithSubscribe(x => recorder3.OnNext(x)); cmd.Execute("a"); testScheduler.AdvanceBy(10); disposable1.Dispose(); cmd.Execute("b"); testScheduler.AdvanceBy(10); disposable2.Dispose(); cmd.Execute("c"); recorder1.Messages.Is( OnNext(0, "a")); recorder2.Messages.Is( OnNext(0, "a"), OnNext(10, "b")); recorder3.Messages.Is( OnNext(0, "a"), OnNext(10, "b"), OnNext(20, "c")); }
public void ReactiveCommandAllFlow() { var testScheduler = new TestScheduler(); var @null = (object)null; var recorder1 = testScheduler.CreateObserver <object>(); var recorder2 = testScheduler.CreateObserver <object>(); var cmd = new ReactiveCommand(); cmd.Subscribe(recorder1); cmd.Subscribe(recorder2); cmd.CanExecute().Is(true); cmd.Execute(); testScheduler.AdvanceBy(10); cmd.Execute(); testScheduler.AdvanceBy(10); cmd.Execute(); testScheduler.AdvanceBy(10); cmd.Dispose(); cmd.CanExecute().Is(false); cmd.Dispose(); // dispose again recorder1.Messages.Is( OnNext(0, @null), OnNext(10, @null), OnNext(20, @null), OnCompleted <object>(30)); recorder2.Messages.Is( OnNext(0, @null), OnNext(10, @null), OnNext(20, @null), OnCompleted <object>(30)); }
public void ReactiveCommandAllFlow() { var testScheduler = new TestScheduler(); var @null = (object)null; var recorder1 = testScheduler.CreateObserver<object>(); var recorder2 = testScheduler.CreateObserver<object>(); var cmd = new ReactiveCommand(); cmd.Subscribe(recorder1); cmd.Subscribe(recorder2); cmd.CanExecute().Is(true); cmd.Execute(); testScheduler.AdvanceBy(10); cmd.Execute(); testScheduler.AdvanceBy(10); cmd.Execute(); testScheduler.AdvanceBy(10); cmd.Dispose(); cmd.CanExecute().Is(false); cmd.Dispose(); // dispose again recorder1.Messages.Is( OnNext(0, @null), OnNext(10, @null), OnNext(20, @null), OnCompleted<object>(30)); recorder2.Messages.Is( OnNext(0, @null), OnNext(10, @null), OnNext(20, @null), OnCompleted<object>(30)); }
// Start is called before the first frame update void Start() { var reactiveCommand = new ReactiveCommand <int>(); reactiveCommand.Where(x => x % 2 == 0).Subscribe(x => Debug.LogFormat("{0} 是 偶数", x)); reactiveCommand.Where(x => x % 2 != 0).Timestamp().Subscribe(x => Debug.LogFormat("{0} 是基数数 {1}", x.Value, x.Timestamp)); reactiveCommand.Execute(10); reactiveCommand.Execute(11); }
// Use this for initialization void Start() { Subject <bool> subject = new Subject <bool>(); ReactiveCommand <string> reactiveCommand = new ReactiveCommand <string>(subject); reactiveCommand.Execute("1"); reactiveCommand.Subscribe(s => print(s)); reactiveCommand.Execute("2"); }
public bool Remove <TData>() { var result = _data.Remove <TData>(); if (result) { _portValueChanged.Execute(Unit.Default); } return(result); }
void Start() { ReactiveCommand command = new ReactiveCommand(); command.Subscribe(_ => { Debug.Log("Command executed!"); }); command.Execute(); command.Execute(); }
void Start() { //这里判定的是 Int 值,是否满足要求。然后 DoSomething... // 同样因为可传泛型,所以也可是对 Object 进行处理,可用性极强 var command = new ReactiveCommand <int>(); //响应命令,可传泛型 command.Where(_ => _ % 2 == 0).Subscribe(_ => print(_ + ">>>>>>能整除")); //增加 时间标记后,形参发生变化,需要指明 value 与 timestamp command.Where(_ => _ % 2 != 0).Timestamp().Subscribe(_ => print(_.Value + ">>>>>>不能" + _.Timestamp)); command.Execute(8); command.Execute(9); }
public void CreateTaskFacilitatesTPLIntegrationWithParameter() { ReactiveCommand <int, int> fixture = ReactiveCommand.CreateFromTask <int, int>(param => Task.FromResult(param + 1), outputScheduler: ImmediateScheduler.Instance); fixture.ToObservableChangeSet(ImmediateScheduler.Instance).Bind(out ReadOnlyObservableCollection <int> results).Subscribe(); fixture.Execute(3).Subscribe(); fixture.Execute(41).Subscribe(); Assert.Equal(2, results.Count); Assert.Equal(4, results[0]); Assert.Equal(42, results[1]); }
// Start is called before the first frame update void Start() { var reactiveCommand = new ReactiveCommand(); reactiveCommand.Subscribe(_ => { Debug.Log("Execute"); }); reactiveCommand.Execute(); reactiveCommand.Execute(); reactiveCommand.Execute(); }
public ServiceViewModel(ServiceBase service) { Name = service.ServiceName; //Get an observable for the current state var currentStateObs = this.ObservableForProperty(x => x.CurrentState).Value().StartWith(ServiceState.Stopped); //Map an observable to IsBusy that is True if the current state is *ing currentStateObs.Select ( s => s == ServiceState.Pausing || s == ServiceState.Starting || s == ServiceState.Stopping ) .Subscribe(busy => IsBusy = busy); StartCommand = new ReactiveCommand(currentStateObs.Select(s => s == ServiceState.Stopped)); StopCommand = new ReactiveCommand(currentStateObs.Select(s => s == ServiceState.Started || s == ServiceState.Paused)); PauseCommand = new ReactiveCommand(currentStateObs.Select(s => s == ServiceState.Started && service.CanPauseAndContinue)); ContinueCommand = new ReactiveCommand(currentStateObs.Select(s => s == ServiceState.Paused && service.CanPauseAndContinue)); AssignmentSubscription(StartCommand, () => ServiceBaseHelpers.StartService(service)); AssignmentSubscription(StopCommand, () => ServiceBaseHelpers.StopService(service)); AssignmentSubscription(PauseCommand, () => ServiceBaseHelpers.PauseService(service)); AssignmentSubscription(ContinueCommand, () => ServiceBaseHelpers.ContinueService(service)); // // Start on start time // StartCommand.Execute(null); }
public void CompletelyDefaultReactiveCommandShouldFire() { var sched = new TestScheduler(); var fixture = new ReactiveCommand(null, sched); Assert.IsTrue(fixture.CanExecute(null)); string result = null; fixture.Subscribe(x => result = x as string); fixture.Execute("Test"); sched.Start(); Assert.AreEqual("Test", result); fixture.Execute("Test2"); sched.Start(); Assert.AreEqual("Test2", result); }
private void InputClicked(object sender, EventArgs e, ReactiveCommand <int, Unit> command, int value, string title) { var inputDialog = new AlertDialog.Builder(this); EditText userInput = new EditText(this); userInput.Text = value.ToString(); userInput.InputType = Android.Text.InputTypes.NumberFlagDecimal | Android.Text.InputTypes.ClassNumber; userInput.SetPadding(25, 25, 25, 25); inputDialog.SetTitle(title); inputDialog.SetView(userInput); inputDialog.SetPositiveButton( "Ok", (see, ess) => { if (!String.IsNullOrEmpty(userInput.Text) && userInput.Text != "0") { int parsedInput = int.Parse(userInput.Text); command.Execute(parsedInput).Subscribe(); } this.HideKeyboard(userInput); }); inputDialog.Show(); this.ShowKeyboard(userInput); }
public ServiceViewModel(ServiceBase service) { Name = service.ServiceName; //Get an observable for the current state var currentStateObs = this.ObservableForProperty(x => x.CurrentState).Value().StartWith(ServiceState.Stopped); //Map an observable to IsBusy that is True if the current state is *ing currentStateObs.Select ( s => s == ServiceState.Pausing || s == ServiceState.Starting || s == ServiceState.Stopping ) .Subscribe(busy => IsBusy = busy); StartCommand = new ReactiveCommand(currentStateObs.Select(s => s == ServiceState.Stopped)); StopCommand = new ReactiveCommand(currentStateObs.Select(s => s == ServiceState.Started || s == ServiceState.Paused)); PauseCommand = new ReactiveCommand(currentStateObs.Select(s => s == ServiceState.Started && service.CanPauseAndContinue)); ContinueCommand = new ReactiveCommand(currentStateObs.Select(s => s == ServiceState.Paused && service.CanPauseAndContinue)); AssignmentSubscription(StartCommand, () => ServiceBaseHelpers.StartService(service)); AssignmentSubscription(StopCommand, () => ServiceBaseHelpers.StopService(service)); AssignmentSubscription(PauseCommand, () => ServiceBaseHelpers.PauseService(service)); AssignmentSubscription(ContinueCommand, () => ServiceBaseHelpers.ContinueService(service)); // // Start on start time // StartCommand.Execute(null); }
private void OnStartClickedProxy() { _startButton.interactable = false; _startButton.GetComponent <Pulse>().Stop(); OnStartClicked.Execute(); }
public PatcherProgressViewModel(string itemID, string installDirectory, IScreen?screen = null) { HostScreen = screen ?? Locator.Current.GetService <IScreen>(); Activator = new ViewModelActivator(); patch = ReactiveCommand.CreateFromObservable(DownloadGoogleDriveFile); this.itemID = itemID; this.installDirectory = installDirectory; this.WhenActivated(disposable => { patch .ThrownExceptions .Subscribe(ex => HostScreen.Router.Navigate.Execute(new PatcherResultViewModel(Result.Failure, ex.Message, HostScreen)).Subscribe()) .DisposeWith(disposable); patch .Where(v => v >= 100) .Subscribe(ex => HostScreen.Router.Navigate.Execute(new PatcherResultViewModel(Result.Success, "The requested patch was downloaded and applied.", HostScreen)).Subscribe()) .DisposeWith(disposable); patch .Execute() .Subscribe() .DisposeWith(disposable); }); }
void Start() { // 创建鼠标按下事件流,返回true var mouseClickDownStream = Observable.EveryUpdate() .Where(_ => Input.GetMouseButtonDown(0)) .Select(_ => true); // 创建鼠标抬起事件流,返回false var mouseClickUpStream = Observable.EveryUpdate() .Where(_ => Input.GetMouseButtonUp(0)) .Select(_ => false); // 合并事件流 var mergeStream = Observable.Merge(mouseClickDownStream, mouseClickUpStream); // 创建命令 var reactiveCommand = new ReactiveCommand(mergeStream, false); // 订阅命令 reactiveCommand.Subscribe(x => { Debug.Log(x); }); // 订阅Update,执行命令 Observable.EveryUpdate() .Subscribe(_ => { reactiveCommand.Execute(); }); }
void Start() { float Speed = 0; var mouseDownSteam = Observable.EveryUpdate() .Where(_ => Input.GetMouseButtonDown(0)).Select(_ => true); var mouseUpSteam = Observable.EveryUpdate() .Where(_ => Input.GetMouseButtonUp(0)).Select(_ => false); var isMouseUp = Observable.Merge(mouseUpSteam, mouseDownSteam); var reactiveCMD = new ReactiveCommand(isMouseUp, false); Observable.EveryUpdate() .Where(_ => Input.GetMouseButtonUp(0)) .Subscribe(_ => { Speed = 0f; }); reactiveCMD.Subscribe(_ => { Speed += 0.1f; Debug.LogFormat("reactive command execute{0}", Speed); }); Observable.EveryUpdate() .Where(_ => Speed < 10f) .Subscribe(_ => { reactiveCMD.Execute(); }); }
public SessionViewModel(SessionModel model ,IPersonFactory<Person> personFactory) { _model = model.ThrowIfNull("model"); _personFactory = personFactory.ThrowIfNull("personFactory"); AddNewPersonCommand = new ReactiveCommand(); AddNewPersonCommand.Subscribe(dontcare => _model.Participants.Add(_personFactory.GetNewPerson(Participants.Count))); Participants = _model.Participants .CreateDerivedCollection(x => new ParticipantViewModel(x)); Participants.ChangeTrackingEnabled = true; var deleteCanExecute = Observable.Merge(Participants.ItemChanged .Select(_ => Participants.Any(p => p.IsSelected)), Participants.CollectionCountChanged .Select(_ => Participants.Any(p=> p.IsSelected))); DeleteSelectedCommand = new ReactiveCommand ( deleteCanExecute ); DeleteSelectedCommand.Subscribe( x => { RemoveSelected(); } ); AddNewPersonCommand.Execute(null); }
public void ObservableExecuteFuncShouldBeObservableAndAct() { var executed_params = new List <object>(); var fixture = new ReactiveCommand(); fixture.Subscribe(x => executed_params.Add(x)); var observed_params = new ReplaySubject <object>(); fixture.Subscribe(observed_params.OnNext, observed_params.OnError, observed_params.OnCompleted); var range = Enumerable.Range(0, 5); foreach (var v in range) { fixture.Execute(v); } Assert.AreEqual(range.Count(), executed_params.Count); foreach (var v in range.Zip(executed_params.OfType <int>(), (e, a) => new { e, a })) { Assert.AreEqual(v.e, v.a); } range.ToObservable() .Zip(observed_params, (expected, actual) => new { expected, actual }) .Subscribe(x => Assert.AreEqual(x.expected, x.actual)); }
public UserViewModel(User user, ReactiveCommand <UserViewModel> showAnotherCommand) { User = user; ShowAnotherCommand = new ReactiveCommand(); ShowAnotherCommand.Subscribe(_ => showAnotherCommand.Execute(this)); }
// Update is called once per frame void Update() { fpsCounter += Time.deltaTime; if (fpsCounter >= fpsTarget) { fpsCounter = 0; UpdateFrame(wcAnimation.GetAnimationSprites()[animationFrameIndex]); animationFrameIndex++; if (animationFrameIndex >= wcAnimation.Count) { if (mode == Mode.Loop) { animationFrameIndex = 0; } else if (mode == Mode.PlayOnce) { animationFinished.Execute(true); if (destroyOnAnimationFinish != null) { Destroy(destroyOnAnimationFinish); } if (this != null) { Destroy(this); } } } } }
public void MultipleSubscribersShouldntDecrementRefcountBelowZero() { (new TestScheduler()).With(sched => { var fixture = new ReactiveCommand(); var results = new List <int>(); bool[] subscribers = new[] { false, false, false, false, false }; var output = fixture.RegisterAsync(_ => Observable.Return(5).Delay(TimeSpan.FromMilliseconds(5000), sched)); output.Subscribe(x => results.Add(x)); Enumerable.Range(0, 5).Run(x => output.Subscribe(_ => subscribers[x] = true)); Assert.True(fixture.CanExecute(null)); fixture.Execute(null); sched.AdvanceToMs(2000); Assert.False(fixture.CanExecute(null)); sched.AdvanceToMs(6000); Assert.True(fixture.CanExecute(null)); Assert.True(results.Count == 1); Assert.True(results[0] == 5); Assert.True(subscribers.All(x => x)); }); }
public void DisallowConcurrentExecutionTest() { (new TestScheduler()).With(sched => { var fixture = new ReactiveCommand(null, false, sched); Assert.True(fixture.CanExecute(null)); var result = fixture.RegisterAsync(_ => Observable.Return(4).Delay(TimeSpan.FromSeconds(5), sched)) .CreateCollection(); Assert.Equal(0, result.Count); sched.AdvanceToMs(25); Assert.Equal(0, result.Count); fixture.Execute(null); Assert.False(fixture.CanExecute(null)); Assert.Equal(0, result.Count); sched.AdvanceToMs(2500); Assert.False(fixture.CanExecute(null)); Assert.Equal(0, result.Count); sched.AdvanceToMs(5500); Assert.True(fixture.CanExecute(null)); Assert.Equal(1, result.Count); }); }
public void AllowConcurrentExecutionTest() { (new TestScheduler()).With(sched => { var fixture = new ReactiveCommand(null, true, sched); Assert.True(fixture.CanExecute(null)); var result = fixture.RegisterAsync(_ => Observable.Return(4).Delay(TimeSpan.FromSeconds(5), sched)) .CreateCollection(); Assert.Equal(0, result.Count); sched.AdvanceToMs(25); Assert.Equal(0, result.Count); fixture.Execute(null); Assert.True(fixture.CanExecute(null)); Assert.Equal(0, result.Count); sched.AdvanceToMs(2500); Assert.True(fixture.CanExecute(null)); Assert.Equal(0, result.Count); sched.AdvanceToMs(5500); Assert.True(fixture.CanExecute(null)); Assert.Equal(1, result.Count); }); }
private void Start() { var isOpen = new BoolReactiveProperty(false); var command = new ReactiveCommand <string>(isOpen); _ = WaitCommandAsync(command); // isOpen = false なので何も起きない command.Execute("Not work!"); // ReactiveCommandを有効化 isOpen.Value = true; // isOpen = true なのでコマンド実行 command.Execute("Work!"); }
private void Initialize(string dataType, string componentType, string portName) { UpdateDataTypeCommand = new ReactiveCommand(); UpdatePortNameCommand = new ReactiveCommand(); UpdateCompoentTypeCommand = new ReactiveCommand(); DataTypes = UpdateDataTypeCommand .SelectMany(_ => Observable.Start(() => _recordDescriptionRepository.GetDataTypes(componentType, portName)) .Catch((Exception ex) => Messenger.Raise(new InformationMessage("データベースアクセスに失敗しました。", "エラー", "ShowError")))) .Do(_ => DataTypes.ClearOnScheduler()) .SelectMany(_ => _) .ToReactiveCollection(); PortNames = UpdatePortNameCommand .SelectMany(_ => Observable.Start(() => _recordDescriptionRepository.GetPortNames(dataType, componentType)) .Catch((Exception ex) => Messenger.Raise(new InformationMessage("データベースアクセスに失敗しました。", "エラー", "ShowError")))) .Do(_ => PortNames.ClearOnScheduler()) .SelectMany(_ => _) .ToReactiveCollection(); ComponentTypes = UpdateCompoentTypeCommand .SelectMany(_ => Observable.Start(() => _recordDescriptionRepository.GetComponentTypes(dataType, portName)) .Catch((Exception ex) => Messenger.Raise(new InformationMessage("データベースアクセスに失敗しました。", "エラー", "ShowError")))) .Do(_ => ComponentTypes.ClearOnScheduler()) .SelectMany(_ => _) .ToReactiveCollection(); DataType = dataType; PortName = portName; ComponentType = componentType; UpdateDataTypeCommand.Execute(null); UpdatePortNameCommand.Execute(null); UpdateCompoentTypeCommand.Execute(null); }
public PersonListViewModel(IScreen hostScreen, IPersonRepository personRepository = null) { HostScreen = hostScreen; personRepository = personRepository ?? new PersonRepository(); Persons = new ReactiveList<PersonItemViewModel>(); NewPersonCommand = new ReactiveCommand(null); NewPersonCommand.RegisterAsyncAction(_ => { }).Subscribe(_ => HostScreen.Router.Navigate.Execute(new PersonAddViewModel(HostScreen))); RefreshCommand = new ReactiveCommand(null); var refresh = RefreshCommand.RegisterAsync<List<Person>>(_ => Observable.Start(() => personRepository.RetrievePersonsAsync(). Result)); refresh.Subscribe(list => { using (Persons.SuppressChangeNotifications()) { Persons.Clear(); Persons.AddRange(personRepository.RetrievePersonsAsync(). Result.Select(d => new PersonItemViewModel(d.FirstName, d.LastName, d.Age))); } }); MessageBus.Current.Listen<Person>(). Subscribe(p => { personRepository.AddPerson(p); RefreshCommand.Execute(null); }); }
public void RAOShouldActuallyRunOnTheTaskpool() { var deferred = RxApp.MainThreadScheduler; var taskpool = RxApp.TaskpoolScheduler; try { var testDeferred = new CountingTestScheduler(Scheduler.Immediate); var testTaskpool = new CountingTestScheduler(Scheduler.NewThread); RxApp.MainThreadScheduler = testDeferred; RxApp.TaskpoolScheduler = testTaskpool; var fixture = new ReactiveCommand(); var result = fixture.RegisterAsync(x => Observable.Return((int)x * 5).Delay(TimeSpan.FromSeconds(1), RxApp.TaskpoolScheduler)); fixture.Execute(1); Assert.Equal(5, result.First()); Assert.True(testDeferred.ScheduledItems.Count >= 1); Assert.True(testTaskpool.ScheduledItems.Count >= 1); } finally { RxApp.MainThreadScheduler = deferred; RxApp.TaskpoolScheduler = taskpool; } }
public void RAFShouldActuallyRunOnTheTaskpool() { var deferred = RxApp.MainThreadScheduler; var taskpool = RxApp.TaskpoolScheduler; try { var testDeferred = new CountingTestScheduler(Scheduler.Immediate); var testTaskpool = new CountingTestScheduler(Scheduler.NewThread); RxApp.MainThreadScheduler = testDeferred; RxApp.TaskpoolScheduler = testTaskpool; var fixture = new ReactiveCommand(); var result = fixture.RegisterAsyncFunction(x => { Thread.Sleep(1000); return((int)x * 5); }); fixture.Execute(1); Assert.Equal(5, result.First()); Assert.True(testDeferred.ScheduledItems.Count >= 1); Assert.True(testTaskpool.ScheduledItems.Count >= 1); } finally { RxApp.MainThreadScheduler = deferred; RxApp.TaskpoolScheduler = taskpool; } }
public override void Setup() { base.Setup(); _confirmButton.OnClickAsObservable() .Subscribe(_ => OnResetConfirmClicked.Execute()) .AddTo(this); }
void Start() { var reactiveCommand = new ReactiveCommand <int>(); reactiveCommand.Where(x => x % 2 == 0).Subscribe(x => { Debug.LogFormat("{0} 是偶数", x); }); reactiveCommand.Where(x => x % 2 == 1).Timestamp().Subscribe(x => { Debug.LogFormat("{0} 是奇数 {1}", x.Value, x.Timestamp); }); reactiveCommand.Execute(2); reactiveCommand.Execute(3); }
public void CanExecuteShouldChangeOnInflightOp() { (new TestScheduler()).With(sched => { var canExecute = sched.CreateHotObservable( sched.OnNextAt(0, true), sched.OnNextAt(250, false), sched.OnNextAt(500, true), sched.OnNextAt(750, false), sched.OnNextAt(1000, true), sched.OnNextAt(1100, false) ); var fixture = new ReactiveCommand(canExecute); int calculatedResult = -1; bool latestCanExecute = false; fixture.RegisterAsync(x => Observable.Return((int)x*5).Delay(TimeSpan.FromMilliseconds(900), RxApp.MainThreadScheduler)) .Subscribe(x => calculatedResult = x); fixture.CanExecuteObservable.Subscribe(x => latestCanExecute = x); // CanExecute should be true, both input observable is true // and we don't have anything inflight sched.AdvanceToMs(10); Assert.True(fixture.CanExecute(1)); Assert.True(latestCanExecute); // Invoke a command 10ms in fixture.Execute(1); // At 300ms, input is false sched.AdvanceToMs(300); Assert.False(fixture.CanExecute(1)); Assert.False(latestCanExecute); // At 600ms, input is true, but the command is still running sched.AdvanceToMs(600); Assert.False(fixture.CanExecute(1)); Assert.False(latestCanExecute); // After we've completed, we should still be false, since from // 750ms-1000ms the input observable is false sched.AdvanceToMs(900); Assert.False(fixture.CanExecute(1)); Assert.False(latestCanExecute); Assert.Equal(-1, calculatedResult); sched.AdvanceToMs(1010); Assert.True(fixture.CanExecute(1)); Assert.True(latestCanExecute); Assert.Equal(calculatedResult, 5); sched.AdvanceToMs(1200); Assert.False(fixture.CanExecute(1)); Assert.False(latestCanExecute); }); }
public DispatchViewModel(IScreen screen, ISession session) { HostScreen = screen; GoBack = HostScreen.Router.NavigateBack; Techs = new ReactiveList<Employee>(); Tickets = new ReactiveList<Ticket>(); var getFreshTechs = new ReactiveCommand(); getFreshTechs.ObserveOn(RxApp.MainThreadScheduler).Subscribe(_ => { Techs.Clear(); session.FetchResults<Employee>() .ObserveOn(RxApp.MainThreadScheduler) .Subscribe(x => Techs.Add(x)); }); var getFreshTickets = new ReactiveCommand(); getFreshTickets.ObserveOn(RxApp.MainThreadScheduler).Subscribe(_ => { Tickets.Clear(); session.FetchResults<Ticket>() .ObserveOn(RxApp.MainThreadScheduler) .Subscribe(x => Tickets.Add(x)); }); Refresh = new ReactiveCommand(session.IsWorking.Select(x => !x)); Refresh.Subscribe(_ => { getFreshTechs.Execute(default(object)); getFreshTickets.Execute(default(object)); }); Assign = new ReactiveCommand(Observable.CombineLatest( this.WhenAny( x => x.SelectedEmployee, y => y.SelectedTicket, (x, y) => x.Value != null && y.Value != null), Refresh.CanExecuteObservable, (x, y) => x && y)); Assign.Subscribe(_ => { using (session.ScopedChanges()) { var eventTaker = session.Take<TicketEvent>(); eventTaker.Add(new TicketEvent { Employee = SelectedEmployee, Ticket = SelectedTicket, TicketStatus = TicketStatus.Assigned, Time = DateTime.Now }); } }); _error = session.ThrownExceptions .Select(x => x.Message) .ObserveOn(RxApp.MainThreadScheduler) .ToProperty(this, x => x.Error); Refresh.Execute(default(object)); }
public void Command_Test() { //Given string result = null; string expected = Any.Create<string>(); ICommand command = new ReactiveCommand<string>(t => result = t, _ => true); //When bool canExecute = command.CanExecute(null); command.Execute(expected); //Then Assert.That(expected, Is.EqualTo(result)); Assert.That(canExecute, Is.True); }
public void CommandCanExecute_Test() { //Given string result = null; string expected = Any.Create<string>(); ICommand command = new ReactiveCommand<string>(t => result = t, _ => false); //When bool canExecute = command.CanExecute(null); command.Execute(expected); //Then Assert.That(canExecute, Is.False); Assert.That(result, Is.Null); }
public SettingsWindowViewModel() { CloseCommand = new ReactiveCommand(); ExceptionCommand = new ReactiveCommand(); KeyCommand = new ReactiveCommand(); KeyCommand.Subscribe(x => { var tuple = x as Tuple<string, HotKey>; if (tuple.Item2 == null) return; App.HotKeyManager.Unregister(Settings.ScreenKey); App.HotKeyManager.Unregister(Settings.SelectionKey); var tmpScreenKey = Settings.ScreenKey; var tmpSelectionKey = Settings.SelectionKey; switch (tuple.Item1) { case "ScreenKey": tmpScreenKey = tuple.Item2; break; case "SelectionKey": tmpSelectionKey = tuple.Item2; break; } App.HotKeyManager.Register(tmpScreenKey); App.HotKeyManager.Register(tmpSelectionKey); // Only apply the change if there hasn't been an error registering them Settings.GetType().GetProperty(tuple.Item1).SetValue(Settings, tuple.Item2); }); KeyCommand.ThrownExceptions.Subscribe(ex => { // We have to re-register the hotkeys here so // that both are registered with the system App.HotKeyManager.Unregister(Settings.ScreenKey); App.HotKeyManager.Unregister(Settings.SelectionKey); App.HotKeyManager.Register(Settings.ScreenKey); App.HotKeyManager.Register(Settings.SelectionKey); ExceptionCommand.Execute(ex); }); App.Settings.Changed.Subscribe(_ => this.RaisePropertyChanged("Settings")); }
public void FullCommand_Test() { //Given const string message = "Reactive"; string result = null; bool completed = false; Exception exception = null; string expected = Any.Create<string>(); var command = new ReactiveCommand<string>(t => result = t, _ => true,ex => exception = ex,() => completed = true ); //When bool canExecute = command.CanExecute(null); command.Execute(expected); command.OnError(new Exception(message)); command.OnCompleted(); //Then Assert.True(canExecute); Assert.AreEqual(result, expected); Assert.That(exception.Message, Is.EqualTo(message)); Assert.True(completed); }
public void ObservableExecuteFuncShouldBeObservableAndAct() { var executed_params = new List<object>(); var fixture = new ReactiveCommand(); fixture.Subscribe(x => executed_params.Add(x)); var observed_params = new ReplaySubject<object>(); fixture.Subscribe(observed_params.OnNext, observed_params.OnError, observed_params.OnCompleted); var range = Enumerable.Range(0, 5); foreach (var v in range) fixture.Execute(v); Assert.AreEqual(range.Count(), executed_params.Count); foreach (var v in range.Zip(executed_params.OfType<int>(), (e, a) => new { e, a })) { Assert.AreEqual(v.e, v.a); } range.ToObservable() .Zip(observed_params, (expected, actual) => new { expected, actual }) .Subscribe(x => Assert.AreEqual(x.expected, x.actual)); }
public PreviewWindowViewModel(string file) { ImageSource = file; SaveDlgCommand = new ReactiveCommand(); CloseCommand = new ReactiveCommand(); UploadCommand = new ReactiveCommand(); UploadCommand.Subscribe(async _ => { CloseCommand.Execute(null); await App.Uploader.Upload(file); }); SaveFileCommand = new ReactiveCommand(); SaveFileCommand.Subscribe(async x => { var saveFile = x as string; if (String.IsNullOrEmpty(saveFile)) return; await Task.Run(() => { using (var image = new Bitmap(ImageSource)) { switch (App.Settings.ImageFormat) { case ImageFormats.Png: image.Save(saveFile, ImageFormat.Png); break; case ImageFormats.Jpg: var encoder = ImageCodecInfo.GetImageEncoders().FirstOrDefault(c => c.FormatID == ImageFormat.Jpeg.Guid); using (var encParams = new EncoderParameters(1)) { encParams.Param[0] = new EncoderParameter(Encoder.Quality, App.Settings.ImageQuality); if (encoder != null) image.Save(saveFile, encoder, encParams); } break; case ImageFormats.Bmp: image.Save(saveFile, ImageFormat.Bmp); break; } } }); }); }
public void RAOShouldActuallyRunOnTheTaskpool() { var deferred = RxApp.MainThreadScheduler; var taskpool = RxApp.TaskpoolScheduler; try { var testDeferred = new CountingTestScheduler(Scheduler.Immediate); var testTaskpool = new CountingTestScheduler(Scheduler.NewThread); RxApp.MainThreadScheduler = testDeferred; RxApp.TaskpoolScheduler = testTaskpool; var fixture = new ReactiveCommand(); var result = fixture.RegisterAsync(x => Observable.Return((int)x*5).Delay(TimeSpan.FromSeconds(1), RxApp.TaskpoolScheduler)); fixture.Execute(1); Assert.Equal(5, result.First()); Assert.True(testDeferred.ScheduledItems.Count >= 1); Assert.True(testTaskpool.ScheduledItems.Count >= 1); } finally { RxApp.MainThreadScheduler = deferred; RxApp.TaskpoolScheduler = taskpool; } }
public void RegisterAsyncFunctionSmokeTest() { (new TestScheduler()).With(sched => { var fixture = new ReactiveCommand(); IReactiveDerivedList<int> results; results = fixture.RegisterAsync(_ => Observable.Return(5).Delay(TimeSpan.FromSeconds(5), sched)).CreateCollection(); var inflightResults = fixture.IsExecuting.CreateCollection(); sched.AdvanceToMs(10); Assert.True(fixture.CanExecute(null)); fixture.Execute(null); sched.AdvanceToMs(1005); Assert.False(fixture.CanExecute(null)); sched.AdvanceToMs(5100); Assert.True(fixture.CanExecute(null)); new[] {false, true, false}.AssertAreEqual(inflightResults); new[] {5}.AssertAreEqual(results); }); }
public TaxonManagementVM( IConnectivityService Connectivity, ITaxonService Taxa, IDiversityServiceClient Service, INotificationService Notification ) { this.Connectivity = Connectivity; this.Service = Service; this.Taxa = Taxa; this.Notification = Notification; _IsOnlineAvailable = this.ObservableToProperty(Connectivity.WifiAvailable(), x => x.IsOnlineAvailable); var localLists = this.FirstActivation() .SelectMany(_ => Taxa.getTaxonSelections() .ToObservable(ThreadPoolScheduler.Instance) .Select(list => new TaxonListVM(list))) .Publish(); LocalLists = localLists .ObserveOnDispatcher() .CreateCollection(); var onlineLists = localLists .IgnoreElements() //only download lists once the local ones are loaded .Concat(Observable.Return(null as TaxonListVM)) .CombineLatest(this.OnActivation(), (_, _2) => _2) .CheckConnectivity(Connectivity, Notification) .SelectMany(_ => { return Service.GetTaxonLists() .DisplayProgress(Notification, DiversityResources.TaxonManagement_State_DownloadingLists) .TakeUntil(this.OnDeactivation()); }) .ObserveOnDispatcher() .SelectMany(lists => lists.Where(list => !LocalLists.Any(loc => loc.Model == list)) // Filter lists already present locally .Select(list => new TaxonListVM(list)) ) .Publish(); PersonalLists = onlineLists.Where(vm => !vm.Model.IsPublicList) .CreateCollection(); PublicLists = onlineLists.Where(vm => vm.Model.IsPublicList) .CreateCollection(); onlineLists.Connect(); localLists.Connect(); Select = new ReactiveCommand<TaxonListVM>(vm => !vm.IsSelected && !vm.IsDownloading); Select.Subscribe(taxonlist => { foreach (var list in LocalLists) { if (list.Model.TaxonomicGroup == taxonlist.Model.TaxonomicGroup) list.Model.IsSelected = false; } Taxa.selectTaxonList(taxonlist.Model); }); Download = new ReactiveCommand<TaxonListVM>(vm => !vm.IsDownloading); Download .CheckConnectivity(Connectivity, Notification) .Subscribe(taxonlist => { if (Taxa.getTaxonTableFreeCount() > 0) { CurrentPivot = Pivot.Local; taxonlist.IsDownloading = true; makeListLocal(taxonlist); DownloadTaxonList(taxonlist) .DisplayProgress(Notification, DiversityResources.TaxonManagement_State_DownloadingList) .ObserveOnDispatcher() .ShowServiceErrorNotifications(Notification) .Subscribe(_ => { //Download Succeeded taxonlist.IsDownloading = false; if (Select.CanExecute(taxonlist)) Select.Execute(taxonlist); }, _ => //Download Failed { taxonlist.IsDownloading = false; removeLocalList(taxonlist); }, () => { }); } }); Delete = new ReactiveCommand<TaxonListVM>(vm => !vm.IsDownloading); Delete .Subscribe(taxonlist => { removeLocalList(taxonlist); }); Refresh = new ReactiveCommand<TaxonListVM>(vm => !vm.IsDownloading); Refresh .Subscribe(taxonlist => { if (Delete.CanExecute(taxonlist)) //Deletes synchronously Delete.Execute(taxonlist); if (Download.CanExecute(taxonlist)) Download.Execute(taxonlist); }); //Download all only on Personal pivot var canDownloadAll = this.WhenAny(x => x.CurrentPivot, x => x.GetValue()) .Select(p => p == Pivot.Personal) .CombineLatest(Connectivity.WifiAvailable(), (p, wi) => p && wi); DownloadAll = new ReactiveCommand(canDownloadAll, initialCondition: false); DownloadAll .SelectMany(_ => PersonalLists.ToArray()) .Where(vm => Download.CanExecute(vm)) .Subscribe(Download.Execute); }
public void MultipleResultsFromObservableShouldntDecrementRefcountBelowZero() { (new TestScheduler()).With(sched => { bool latestExecuting = false; var fixture = new ReactiveCommand(null, false, sched); var results = fixture .RegisterAsync(_ => new[] {1, 2, 3}.ToObservable()) .CreateCollection(); fixture.IsExecuting.Subscribe(x => latestExecuting = x); fixture.Execute(1); sched.Start(); Assert.Equal(3, results.Count); Assert.Equal(false, latestExecuting); }); }
public void MultipleSubscribersShouldntDecrementRefcountBelowZero() { (new TestScheduler()).With(sched => { var fixture = new ReactiveCommand(); var results = new List<int>(); bool[] subscribers = new[] {false, false, false, false, false}; var output = fixture.RegisterAsync(_ => Observable.Return(5).Delay(TimeSpan.FromMilliseconds(5000), sched)); output.Subscribe(x => results.Add(x)); Enumerable.Range(0, 5).Run(x => output.Subscribe(_ => subscribers[x] = true)); Assert.True(fixture.CanExecute(null)); fixture.Execute(null); sched.AdvanceToMs(2000); Assert.False(fixture.CanExecute(null)); sched.AdvanceToMs(6000); Assert.True(fixture.CanExecute(null)); Assert.True(results.Count == 1); Assert.True(results[0] == 5); Assert.True(subscribers.All(x => x)); }); }
private void Initialize(string dataType, string componentType, string portName) { UpdateDataTypeCommand = new ReactiveCommand(); UpdatePortNameCommand = new ReactiveCommand(); UpdateCompoentTypeCommand = new ReactiveCommand(); DataTypes = UpdateDataTypeCommand .SelectMany(_=>Observable.Start(()=>_recordDescriptionRepository.GetDataTypes(componentType,portName)) .Catch((Exception ex) => Messenger.Raise(new InformationMessage("データベースアクセスに失敗しました。", "エラー", "ShowError")))) .Do(_ => DataTypes.ClearOnScheduler()) .SelectMany(_=>_) .ToReactiveCollection(); PortNames = UpdatePortNameCommand .SelectMany(_=>Observable.Start(()=>_recordDescriptionRepository.GetPortNames(dataType,componentType)) .Catch((Exception ex) => Messenger.Raise(new InformationMessage("データベースアクセスに失敗しました。", "エラー", "ShowError")))) .Do(_ => PortNames.ClearOnScheduler()) .SelectMany(_=>_) .ToReactiveCollection(); ComponentTypes = UpdateCompoentTypeCommand .SelectMany(_=>Observable.Start(()=>_recordDescriptionRepository.GetComponentTypes(dataType,portName)) .Catch((Exception ex) => Messenger.Raise(new InformationMessage("データベースアクセスに失敗しました。", "エラー", "ShowError")))) .Do(_ => ComponentTypes.ClearOnScheduler()) .SelectMany(_=>_) .ToReactiveCollection(); DataType = dataType; PortName = portName; ComponentType = componentType; UpdateDataTypeCommand.Execute(null); UpdatePortNameCommand.Execute(null); UpdateCompoentTypeCommand.Execute(null); }
public MainWindowViewModel() { ImageHistory = new ReactiveList<string>(); VisiblityCommand = new ReactiveCommand(); DropCommand = new ReactiveCommand(); SettingsCommand = new ReactiveCommand(); UploadCommand = new ReactiveCommand(); ScreenCommand = new ReactiveCommand(); SelectionCommand = new ReactiveCommand(this.WhenAnyValue(x => x.IsCaptureWindowOpen).Select(x => !x)); SelectionCommand.Subscribe(_ => IsCaptureWindowOpen = true); DropCommand.Subscribe(async ev => { var e = ev as DragEventArgs; if (e == null) return; if (!e.Data.GetDataPresent(DataFormats.FileDrop)) return; var data = e.Data.GetData(DataFormats.FileDrop) as IEnumerable<string>; if (data == null) return; foreach (var file in data) await App.Uploader.Upload(file); }); OpenCommand = new ReactiveCommand(); OpenCommand.Subscribe(async files => { foreach (var file in (IEnumerable<string>)files) await App.Uploader.Upload(file); }); MessageBus.Current.Listen<object>("CaptureWindow").Subscribe(_ => IsCaptureWindowOpen = false); Observable.FromEventPattern<KeyPressedEventArgs>(handler => App.HotKeyManager.KeyPressed += handler, handler => App.HotKeyManager.KeyPressed -= handler).Select(x => x.EventArgs).Subscribe(e => { var hk = e.HotKey; if (hk.Equals(App.Settings.ScreenKey)) ScreenCommand.Execute(null); else if (hk.Equals(App.Settings.SelectionKey)) { if (SelectionCommand.CanExecute(null)) SelectionCommand.Execute(null); } }); Observable.FromEventPattern<UploaderEventArgs>(handler => App.Uploader.ImageUploadSuccess += handler, handler => App.Uploader.ImageUploadSuccess -= handler).Select(x => x.EventArgs).Subscribe(e => { if (App.Settings.CopyLinks) Clipboard.SetDataObject(e.ImageUrl); ImageHistory.Add(e.ImageUrl); if (!App.Settings.Notifications) return; var msg = string.Format("Image Uploaded: {0}", e.ImageUrl); MessageBus.Current.SendMessage(new NotificationMessage(Title, msg, BalloonIcon.Info)); }); Observable.FromEventPattern<UploaderEventArgs>(handler => App.Uploader.ImageUploadFailed += handler, handler => App.Uploader.ImageUploadFailed -= handler).Select(x => x.EventArgs).Subscribe(e => { if (!App.Settings.Notifications) return; var msg = string.Format("Image Failed: {0}", e.Exception.Message); MessageBus.Current.SendMessage(new NotificationMessage(Title, msg, BalloonIcon.Error)); }); App.Settings.ObservableForProperty(x => x.AlwaysOnTop).Subscribe(_ => this.RaisePropertyChanged("IsTopmost")); }
public void RAFShouldActuallyRunOnTheTaskpool() { var deferred = RxApp.MainThreadScheduler; var taskpool = RxApp.TaskpoolScheduler; try { var testDeferred = new CountingTestScheduler(Scheduler.Immediate); var testTaskpool = new CountingTestScheduler(Scheduler.NewThread); RxApp.MainThreadScheduler = testDeferred; RxApp.TaskpoolScheduler = testTaskpool; var fixture = new ReactiveCommand(); var result = fixture.RegisterAsyncFunction(x => { Thread.Sleep(1000); return (int)x*5; }); fixture.Execute(1); Assert.Equal(5, result.First()); Assert.True(testDeferred.ScheduledItems.Count >= 1); Assert.True(testTaskpool.ScheduledItems.Count >= 1); } finally { RxApp.MainThreadScheduler = deferred; RxApp.TaskpoolScheduler = taskpool; } }