public void ItemsAddedAndRemovedTest() { var fixture = new ReactiveCollection<int>(); var before_added = new List<int>(); var before_removed = new List<int>(); var added = new List<int>(); var removed = new List<int>(); fixture.BeforeItemsAdded.Subscribe(before_added.Add); fixture.BeforeItemsRemoved.Subscribe(before_removed.Add); fixture.ItemsAdded.Subscribe(added.Add); fixture.ItemsRemoved.Subscribe(removed.Add); fixture.Add(10); fixture.Add(20); fixture.Add(30); fixture.RemoveAt(1); fixture.Clear(); var added_results = new[]{10,20,30}; Assert.AreEqual(added_results.Length, added.Count); added_results.AssertSequenceAreEqual(added); var removed_results = new[]{20}; Assert.AreEqual(removed_results.Length, removed.Count); removed_results.AssertSequenceAreEqual(removed); Assert.AreEqual(before_added.Count, added.Count); added.AssertSequenceAreEqual(before_added); Assert.AreEqual(before_removed.Count, removed.Count); removed.AssertSequenceAreEqual(before_removed); }
// Start is called before the first frame update void Start() { var collection = new ReactiveCollection <string>(); collection.ObserveAdd().Subscribe(x => Debug.Log(string.Format("Add[{ 0}]={ 1}", x.Index, x.Value))); collection.ObserveRemove().Subscribe(x => Debug.Log(string.Format("Remove[{ 0}]={ 1}", x.Index, x.Value))); collection.Add("Apple"); collection.Add("Baseball"); collection.Add("Cherry"); collection.Remove("Apple"); }
public void DerivedCollectionShouldOrderCorrectly() { var collection = new ReactiveCollection <int>(); var orderedCollection = collection.CreateDerivedCollection(x => x, null, (x, y) => x.CompareTo(y)); collection.Add(1); collection.Add(2); Assert.Equal(2, orderedCollection.Count); Assert.Equal(1, orderedCollection[0]); Assert.Equal(2, orderedCollection[1]); }
// tileを選択 private void SelectTile() { var currentPointData = new PointerEventData(EventSystem.current) { position = Input.mousePosition }; EventSystem.current.RaycastAll(currentPointData, rayResult); // 飛ばしたrayの中にtileが含まれているか var tile = rayResult .Select(x => x.gameObject.GetComponent <ITile>()) .FirstOrDefault(x => x != null); if (tile == null) { return; } audioManager.PlaySE(SfxType.TileClick); var coordinates = tile.Coordinates; var frontTile = tileSpawner.GetTile(coordinates); // 現在の選択するによって場合分け switch (selectedCoordinates.Count()) { case 0: if (frontTile == null) { return; } frontTile.SetIsSelected(true); selectedCoordinates.Add(coordinates); break; case 1: if (selectedCoordinates.Contains(coordinates)) { selectedCoordinates.Remove(coordinates); if (frontTile != null) { frontTile.SetIsSelected(false); } } else { selectedCoordinates.Add(coordinates); } break; } }
public MemoryBrowser(object root) { Kernel.Instance.Inject(this); // TODO prevent simple-values here rxBreadcrumbs.Add(root); Current = root; // this will trigger the UpdateCurrentSnapshot currentProperty.DistinctUntilChanged().Subscribe(_ => { rxCurrentSnapShot.Clear(); UpdateCurrentSnapshot(); }).AddTo(compDisp); }
private void Start() { var rc = new ReactiveCollection <int>(); // 要素が増えた時の通知を購読 rc.ObserveAdd() .Subscribe((CollectionAddEvent <int> a) => { Debug.Log($"Add [{a.Index}]:{a.Value}"); }); // 要素が削除された時の通知を購読 rc.ObserveRemove() .Subscribe((CollectionRemoveEvent <int> r) => { Debug.Log($"Remove [{r.Index}]:{r.Value}"); }); // 要素が更新された時の通知を購読 rc.ObserveReplace() .Subscribe((CollectionReplaceEvent <int> r) => { Debug.Log($"Replace [{r.Index}]:{r.OldValue} -> {r.NewValue}"); }); // 要素数の変化の通知を購読 rc.ObserveCountChanged() .Subscribe((int c) => { Debug.Log($"Count: {c}"); }); // 要素のインデックスが変更された rc.ObserveMove() .Subscribe((CollectionMoveEvent <int> x) => { Debug.Log($"Move {x.Value}:[{x.OldIndex}] -> [{x.NewIndex}]"); }); rc.Add(1); rc.Add(2); rc.Add(3); rc[1] = 5; rc.RemoveAt(0); // Dispose()時に各Observableに // OnCompletedメッセージが発行される rc.Dispose(); }
void Start() { foreach (var url in mNames) { Debug.Log(url); } mNames.ObserveAdd().Subscribe(addUrl => Debug.LogFormat("add {0}", addUrl)); mNames.ObserveRemove().Subscribe(removeUrl => Debug.LogFormat("remove {0}", removeUrl)); mNames.ObserveCountChanged().Subscribe(count => Debug.LogFormat("count {0}", count)); mNames.Add("*****@*****.**"); mNames.Add("Chauncy"); mNames.Remove("John_Q"); }
public DummySettingViewModel() { PhotoFolders = new ReactiveCollection <PhotoFolder>().AddTo(Disposable); PhotoFolders.Add(new PhotoFolder { FolderPath = @"C:\\Test", ContainsSubFolder = false }); PhotoFolders.Add(new PhotoFolder { FolderPath = @"C:\\Hoge\\VRChat", ContainsSubFolder = true }); CacheDataSize = new ReactiveProperty <string>("00 MB").AddTo(Disposable); CacheFolderPath = new ReactiveProperty <string>(@"C:\\Hoge\\Piyo").AddTo(Disposable); CanEnter = new ReactiveProperty <bool>(false).AddTo(Disposable); InternationalDateLine = new ReactiveProperty <DateTime>().AddTo(Disposable); MessageText = new ReactiveProperty <string>("Testメッセージです").AddTo(Disposable); }
public RxFMPWork() { for (int i = 0; i < _partworks.Length; i++) { _propParts.Add(new RxFMPPartWork()); } }
internal void New() { _selectedGalaxy = new GalaxyModel(); _galaxies.Add(_selectedGalaxy); _player.CreatedGalaxies++; GameModel.Set <GalaxyModel>(_selectedGalaxy); }
public void AddCard(MeatCard card) { if (_source.Count < maxCount) { _source.Add(card); } }
void Start() { foreach (var item in collection) { Debug.Log(item); } // 集合添加数据时订阅 collection.ObserveAdd() .Subscribe(addValue => { Debug.Log("added " + addValue); }); // 集合移除数据时订阅 collection.ObserveRemove() .Subscribe(removeValue => { Debug.Log("remove " + removeValue); }); // 集合每次数据变动监听每 collection.ObserveCountChanged() .Subscribe(count => { Debug.Log("collection count " + count); }); collection.Add(6); collection.Remove(2); }
void Start() { var player = _manager.Player; // スロットの初期化 for (int i = 0; i < SLOT_SIZE; i++) { _slot.Add(Orb.NONE); } // Update毎にスロット内の情報を更新 this.UpdateAsObservable() .Subscribe(_ => { // MARK : 配列使わないいい方法あるかも var orbs = player.GetOrbsInSlot() .Select(x => x.ToOrb()) .ToArray(); // スロット1つ1つに対して処理 for (int i = 0; i < SLOT_SIZE; i++) { // オーブがスロットより少なかったら空 _slot[i] = i >= orbs.Length ? Orb.NONE : orbs[i]; } }); // 生成されるスキルの更新 player.ObserveEveryValueChanged(x => x.CurrentSkillOutcome()) // 1回目はスルー .Skip(1) .DistinctUntilChanged() .Subscribe(x => _expectedSkill.SetValueAndForceNotify(x)); }
/// <summary> /// カテゴリ文字列を全件検索して、更新があればカテゴリリストを更新する /// </summary> /// <returns>リストを更新したらtrueを返す</returns> public static bool UpdateCategoryList() { var newlist = new List <string>(); if (_categoryList == null) { _categoryList = new ReactiveCollection <string>(); } // ItemsListを全件検索 foreach (var item in ItemsList) { if (!newlist.Contains(item.CategoryR.Value)) { newlist.Add(item.CategoryR.Value); } } newlist.Sort(); // newlistが現行リストと違う場合は更新する if (!newlist.SequenceEqual(_categoryList)) { _categoryList.Clear(); foreach (var s in newlist) { _categoryList.Add(s); } } return(true); }
/// <summary> /// ファイルからメモリストの情報を読み出して引数のリストに追加する /// </summary> /// <param name="memoList">追加する対象のリスト</param> /// <param name="filename">読み出すファイル</param> /// <returns>追加された項目数</returns> public static int LoadMemoFile(ReactiveCollection <SelfMemoItem> memoList, string filename) { int ret = 0; ReactiveCollection <SelfMemoItem> _memo; try { using (var ms = new FileStream(filename, FileMode.Open)) { var serializer = new DataContractJsonSerializer(typeof(ReactiveCollection <SelfMemoItem>)); _memo = (ReactiveCollection <SelfMemoItem>)serializer.ReadObject(ms); } foreach (var m in _memo) { m.Initialize(); if (!memoList.Contains(m)) { memoList.Add(m); ret++; } } } catch (Exception e) { //error } return(ret); }
public ProjectsViewModel(IApplicationService applicationService, IAccountsService accountsService) { Account = accountsService.ActiveAccount; GoToProjectCommand = new ReactiveCommand(); Projects = new ReactiveCollection <Project>(new [] { CreatePersonalProject(accountsService.ActiveAccount) }); LoadCommand.RegisterAsyncTask(async x => { var getAllProjects = applicationService.StashClient.Projects.GetAll(); using (Projects.SuppressChangeNotifications()) { Projects.Clear(); Projects.Add(CreatePersonalProject(accountsService.ActiveAccount)); Projects.AddRange(await getAllProjects.ExecuteAsyncAll()); } }); GoToProjectCommand.OfType <Project>().Subscribe(x => { var vm = this.CreateViewModel <RepositoriesViewModel>(); vm.ProjectKey = x.Key; vm.Name = x.Name; ShowViewModel(vm); }); }
public void InsertRangeSmokeTest() { var fixture = new ReactiveCollection <string>(); var output = fixture.CreateDerivedCollection(x => "Prefix" + x); fixture.Add("Bamf"); Assert.Equal(1, fixture.Count); Assert.Equal(1, output.Count); Assert.Equal("Bamf", fixture[0]); Assert.Equal("PrefixBamf", output[0]); fixture.InsertRange(0, Enumerable.Repeat("Bar", 4)); Assert.Equal(5, fixture.Count); Assert.Equal(5, output.Count); Assert.Equal("Bamf", fixture[4]); Assert.Equal("PrefixBamf", output[4]); Assert.True(fixture.Take(4).All(x => x == "Bar")); Assert.True(output.Take(4).All(x => x == "PrefixBar")); // Trigger the Reset by adding a ton of items fixture.InsertRange(0, Enumerable.Repeat("Bar", 35)); Assert.Equal(40, fixture.Count); Assert.Equal(40, output.Count); Assert.Equal("Bamf", fixture[39]); Assert.Equal("PrefixBamf", output[39]); }
public Session(IReceiver receiver, IAnalysis analysis) { Id = Guid.NewGuid(); Receiver = receiver; DiagnoseOutputEntries = new ReactiveCollection<IDiagnoseOutputEntry>(); Analysis = new ReactiveCollection<IAnalysis>(); Analysis.ItemsAdded.Subscribe(x => { foreach (var diagnoseOutputEntry in DiagnoseOutputEntries) { x.ProcessNewDiagnoseOutputEntry(diagnoseOutputEntry); } }); Analysis.Add(analysis); DiagnoseOutputEntries.ItemsAdded.Subscribe(x => { foreach (var analyse in Analysis) { analyse.ProcessNewDiagnoseOutputEntry(x); } }); }
public void DerivedCollectionsShouldFollowBaseCollection() { var input = new[] { "Foo", "Bar", "Baz", "Bamf" }; var fixture = new ReactiveCollection <TestFixture>( input.Select(x => new TestFixture() { IsOnlyOneWord = x })); var output = fixture.CreateDerivedCollection(new Func <TestFixture, string>(x => x.IsOnlyOneWord)); input.AssertAreEqual(output); fixture.Add(new TestFixture() { IsOnlyOneWord = "Hello" }); Assert.Equal(5, output.Count); Assert.Equal("Hello", output[4]); fixture.RemoveAt(4); Assert.Equal(4, output.Count); fixture[1] = new TestFixture() { IsOnlyOneWord = "Goodbye" }; Assert.Equal(4, output.Count); Assert.Equal("Goodbye", output[1]); fixture.Clear(); Assert.Equal(0, output.Count); }
private void Awake() { audioSource = GetComponent <AudioSource>(); for (var i = 0; i < transform.childCount; i++) { var c = transform.GetChild(i).GetComponent <Candle>(); candleList.Add(c); var r = (int)Random.Range(0, bodyLengthContainer.Count()); c.AddBody(bodyLengthContainer.ElementAt(r)); c.IsPlayable.Where(x => x) .Subscribe(onPlayable => { if (!LitCandleList.Contains(c)) { LitCandleList.Add(c); } PlaySE(); c.BodyCount .TakeUntil(c.BodyCount.Where(x => x == 0)) .Subscribe(count => _bgmPitch.Value = Mathf.InverseLerp(0.2f, 10f, 5 / Mathf.Clamp(count, 1, 5))); }); c.IsPlayable.Where(x => !x) .Subscribe(deActivate => { c.transform.SetParent(transform); }); } }
void handleTouch(Vector3 touchObservable) { // cast a ray from the point we touched out to the board Ray ray = Camera.main.ScreenPointToRay(touchObservable); RaycastHit[] hits = Physics.RaycastAll(ray, 25f, selectMask); // if we didn't hit something the user means to if (hits.Length == 0) { // clear the current selection ClearSelection(); } // otherwise we hit something that could have selectable objects else { // save the first hit var target = hits[0]; var cell = target.collider.GetComponent <WARActorCell>(); // if the target is a cell with contents if (cell != null && cell.objects.Count > 0) { // use the contents as the selection using remove so that subscribers can listen ClearSelection(); // add each object in the cell to the selection foreach (var obj in cell.objects) { Selection.Add(obj); } } } }
public void Shoot(Planet planet, Vector2 direction) { if (planet.currentRocketCooldown > 0) { Debug.LogError("actually can't shoot at the moment"); } planet.currentRocketCooldown = planet.rocketUsed.cooldown; direction.Normalize(); var rocket = planet.rocketUsed; // actually a derivative of planet movement formula var planetSpeed = planet.config.orbitDistance * planet.config.rotationSpeed * new Vector2(-Mathf.Sin(planet.rotationPhase), 0.7f * Mathf.Cos(planet.rotationPhase)); Debug.Log($"planet speed {planetSpeed}"); rockets.Add(new RocketInstance { config = rocket, position = planet.position + direction * planet.config.radius, speed = rocket.startingSpeed * direction + planetSpeed, invulTime = rocket.invulTime, lifeTime = 15, parentId = planet.id }); }
public void AddPlayer(PlayerOther player) { if (CheckJoinRoom(player.clubId.Value)) { roomPlayers.Add(player); } }
public Session(IReceiver receiver, IAnalysis analysis) { Id = Guid.NewGuid(); Receiver = receiver; DiagnoseOutputEntries = new ReactiveCollection <IDiagnoseOutputEntry>(); Analysis = new ReactiveCollection <IAnalysis>(); Analysis.ItemsAdded.Subscribe(x => { foreach (var diagnoseOutputEntry in DiagnoseOutputEntries) { x.ProcessNewDiagnoseOutputEntry(diagnoseOutputEntry); } }); Analysis.Add(analysis); DiagnoseOutputEntries.ItemsAdded.Subscribe(x => { foreach (var analyse in Analysis) { analyse.ProcessNewDiagnoseOutputEntry(x); } }); }
void Start() { var submit = Observable.Merge(_addButton.OnClickAsObservable().Select(_ => _inputField.text), _inputField.OnEndEditAsObservable().Where(_ => Input.GetKeyDown(KeyCode.Return))); submit.Where(_ => _ != "") .Subscribe(_ => { _inputField.text = ""; var item = Instantiate(_itemPrefab); item.GetComponentInChildren <Text>().text = _; _reactives.Add(item); }); _reactives.ObserveCountChanged().Subscribe(_ => _numsText.text = "Count:" + _.ToString()); _reactives.ObserveAdd().Subscribe(_ => { _.Value.SetActive(true); _.Value.transform.SetParent(_listTransform, false); }); _reactives.ObserveRemove().Subscribe(_ => { GameObject.Destroy(_.Value); }); _clearButton.OnClickAsObservable().Subscribe(_ => { var removes = _reactives.Where(__ => __.GetComponent <Toggle>().isOn); removes.ToList().ForEach(___ => _reactives.Remove(___)); }); }
public void Footstep(int index) { if (!Footsteps.Contains(index)) { Footsteps.Add(index); } }
// カードを追加する public void AddCard(MeatCard card) { if (CanAdd(card)) { _agingMeats.Add(card); } }
void Start() { // merge Button click and push enter key on input field. var submit = Observable.Merge( AddButton.OnClickAsObservable().Select(_ => ToDoInput.text), ToDoInput.OnEndEditAsObservable().Where(_ => Input.GetKeyDown(KeyCode.Return))); // add to reactive collection submit.Where(x => x != "") .Subscribe(x => { ToDoInput.text = ""; // clear input field var item = Instantiate(SampleItemPrefab) as GameObject; (item.GetComponentInChildren(typeof(Text)) as Text).text = x; toDos.Add(item); }); // Collection Change Handling toDos.ObserveCountChanged().Subscribe(x => Title.text = "TODO App, ItemCount:" + x); toDos.ObserveAdd().Subscribe(x => { x.Value.transform.SetParent(TodoList.transform, false); }); toDos.ObserveRemove().Subscribe(x => { GameObject.Destroy(x.Value); }); // Clear ClearButton.OnClickAsObservable() .Subscribe(_ => { var removeTargets = toDos.Where(x => x.GetComponent <Toggle>().isOn).ToArray(); foreach (var item in removeTargets) { toDos.Remove(item); } }); }
private void OnJoinedRoom() { if (_playersReactiveCollection == null) { return; } if (_playersReactiveCollection.Count > 0) { _playersReactiveCollection.Clear(); } foreach (var photonPlayer in PhotonNetwork.playerList) { _playersReactiveCollection.Add(photonPlayer); } }
public void Initialize() { for (var i = 0; i < 5; i++) { monsters.Add(new MonsterModel(i + 1)); } }
void IInitializable.Initialize() { if (_settings.Group == null) { return; } foreach (Voice voice in Enum.GetValues(typeof(Voice))) { var clip = _settings.Clips.ElementAt((int)voice); _clips.Add(voice.ToString(), clip); } Observable.Merge( _intent.OnPlayAsObservable().Select(x => x.ToString()), _intent.OnPlayForNameAsObservable()) .Subscribe(x => Play(x).GetAwaiter()) .AddTo(_disposable); _intent.OnStopAsObservable() .Subscribe(_ => _sources.ForEach(x => x.Stop())) .AddTo(_disposable); _volumeIntent.OnVoiceVolumeAsObservable() .Select(x => Mathf.Lerp(-80.0F, 0.0F, Mathf.Clamp01(x))) .Subscribe(x => _settings.Group.audioMixer.SetFloat(_settings.VolumeExposedParameter, x)) .AddTo(_disposable); for (var i = 0; i < _settings.MaxPlayCount; i++) { var audioSource = new GameObject($"Voice_{i:000}").AddComponent <AudioSource>(); audioSource.outputAudioMixerGroup = _settings.Group; _sources.Add(audioSource); } }
private void Window_Drop(object sender, DragEventArgs e) { string[] files = e.Data.GetData(DataFormats.FileDrop) as string[]; if (files != null) { var asm = Assembly.LoadFrom(files[0]); var mod = asm.GetModule(asm.ManifestModule.Name); _uploadModuleClasses = new ReactiveCollection <ClassManager>(); foreach (var definedType in mod.Assembly.DefinedTypes) { if (!definedType.IsPublic) { continue; } var classTypeInfo = definedType; var methods = new ReactiveCollection <MethodManager>(); foreach (var method in definedType.DeclaredMethods) { methods.Add(new MethodManager { Method = method, IsUse = false }); } _uploadModuleClasses.Add(new ClassManager { ClassTypeInfo = definedType, IsUse = true, Methods = methods }); } } lstbxClasses.ItemsSource = _uploadModuleClasses; }
private void FillItemsGrid() { List<AllItemsGridView> ItemsLst = context.AllItemsGridViews.ToList<AllItemsGridView>(); ItemsGrid = new ReactiveCollection<AllItemsGridView>(); foreach (AllItemsGridView igv in ItemsLst) { ItemsGrid.Add(igv); } DeleteItemCommand = new ReactiveCommand(); DeleteItemCommand.OfType<AllItemsGridView>().Subscribe(item => DeleteItem(item)); }
public OrganizationTileViewModel(GitHubOrgInfo model, IObservable<List<GitHubRepo>> repositories) { Model = model; Repositories = new ReactiveCollection<RepoTileViewModel>(); repositories .SelectMany(x => x.ToObservable()) .ObserveOn(RxApp.DeferredScheduler) .Where(x => model.login == x.owner.login) .Subscribe(x => Repositories.Add(new RepoTileViewModel() { Model = x })); }
private void FillItemsGrid() { List<Customer> ItemsLst = context.Customers.ToList<Customer>(); CustsGrid = new ReactiveCollection<Customer>(); foreach (Customer cgv in ItemsLst) { CustsGrid.Add(cgv); } DeleteCustomerCommand = new ReactiveCommand(); DeleteCustomerCommand.OfType<Customer>().Subscribe(customer => DeleteCustomer(customer)); }
public WeeklyTimePeriod(bool[,] timegrid = null) { Hours = new ReactiveCollection<HourlyTimePeriod>(); for (var day = 0; day < DaysPerWeek; day++) { for (var hour = 0; hour < HoursPerDay; hour++) { Hours.Add(new HourlyTimePeriod(day, hour)); } } ResetTimeConfiguration(timegrid); }
public NotificationSettingsViewModel(NotificationSettings notification) { _notification = notification; Notifications = new ReactiveCollection<NotificationViewModel>(); foreach (var notificationEntry in notification.Notifications) { Notifications.Add(new NotificationViewModel(notificationEntry, this)); } AddNotificationCommand = new ReactiveCommand(); AddNotificationCommand.Subscribe(_ => { Notifications.Add(new NotificationViewModel( new NotificationEntry { Triggers = new[] {new NotificationTrigger()}, Actions = new[] {new NotificationAction()} }, this)); Notifications.Last().Actions.First().IsEditing = true; Notifications.Last().Triggers.First().IsEditing = true; }); DeleteNotificationCommand = new ReactiveCommand(); DeleteNotificationCommand.OfType<NotificationViewModel>().Subscribe(n => Notifications.Remove(n)); (ToggleEditCommand = new ReactiveCommand()).Do(_ => Trace.WriteLine(_)).OfType<IToggleEdit>().Subscribe(editable => { bool valueToSet = !editable.IsEditing; foreach (var notificationViewModel in Notifications) { notificationViewModel.CollapseAll(); } editable.IsEditing = valueToSet; }); }
public void CollectionCountChangedTest() { var fixture = new ReactiveCollection<int>(); var before_output = new List<int>(); var output = new List<int>(); fixture.CollectionCountChanging.Subscribe(before_output.Add); fixture.CollectionCountChanged.Subscribe(output.Add); fixture.Add(10); fixture.Add(20); fixture.Add(30); fixture.RemoveAt(1); fixture.Clear(); var before_results = new[] {0,1,2,3,2}; Assert.AreEqual(before_results.Length, before_output.Count); before_results.AssertSequenceAreEqual(before_output); var results = new[]{1,2,3,2,0}; results.AssertSequenceAreEqual(output); }
public NotificationViewModel(NotificationEntry notificationEntry, NotificationSettingsViewModel parent) { _notificationEntry = notificationEntry; _parent = parent; Triggers = new ReactiveCollection<TriggerViewModel>(); foreach (var trigger in notificationEntry.Triggers) { Triggers.Add(new TriggerViewModel(trigger)); } Actions = new ReactiveCollection<ActionViewModel>(); foreach (var notificationAction in notificationEntry.Actions) { Actions.Add(new ActionViewModel(notificationAction)); } AddNewTriggerCommand = new ReactiveCommand(); AddNewTriggerCommand.Subscribe(_ => { Triggers.Add(new TriggerViewModel(new NotificationTrigger())); SelectedTrigger = Triggers.Last(); _parent.ToggleEditCommand.Execute(Triggers.Last()); }); AddNewActionCommand = new ReactiveCommand(); AddNewActionCommand.Subscribe(_ => { Actions.Add(new ActionViewModel(new FlashTaskBarNotificationAction())); SelectedAction = Actions.Last(); _parent.ToggleEditCommand.Execute(Actions.Last()); }); DeleteItemCommand = new ReactiveCommand(); DeleteItemCommand.OfType<TriggerViewModel>().Subscribe(t => Triggers.Remove(t)); DeleteItemCommand.OfType<ActionViewModel>().Subscribe(a => Actions.Remove(a)); }
public CacheViewModel(IScreen hostScreen, IAppState appState) { HostScreen = hostScreen; appState.WhenAny(x => x.CachePath, x => x.Value) .Where(x => !String.IsNullOrWhiteSpace(x)) .Select(x => (new DirectoryInfo(x)).Name) .ToProperty(this, x => x.UrlPathSegment); Keys = new ReactiveCollection<string>(); appState.WhenAny(x => x.CurrentCache, x => x.Value).Subscribe(cache => { Keys.Clear(); cache.GetAllKeys().ForEach(x => Keys.Add(x)); }); SelectedViewer = "Text"; this.WhenAny(x => x.SelectedKey, x => x.SelectedViewer, (k,v) => k.Value) .Where(x => x != null && SelectedViewer != null) .SelectMany(x => appState.CurrentCache.GetAsync(x)) .Select(x => createValueViewModel(x, SelectedViewer)) .LoggedCatch(this, Observable.Return<ICacheValueViewModel>(null)) .ToProperty(this, x => x.SelectedValue); }
private void BindMappingToUi(GamepadMapping mapping) { ListViewMappingItems = new ReactiveCollection<ListViewItem>(); foreach (var mappingItem in mapping.MappingItems) { var item = new ListViewItem { Content = mappingItem, ContentTemplate = DataTemplateForMappingType(mappingItem.Type) }; ListViewMappingItems.Add(item); } MappingItemsListView.ItemsSource = ListViewMappingItems; MappingItemsListView.AlternationCount = ListViewMappingItems.Count + 1; VirtualKeysListViewMappingItems = new ReactiveCollection<ListViewItem>(); foreach (var virtualKeyMappingItem in mapping.VirtualKeysItems) { var item = new ListViewItem { Content = virtualKeyMappingItem, ContentTemplate = (DataTemplate) FindResource("VirtualKeysItemTemplate") }; VirtualKeysListViewMappingItems.Add(item); } VirtualKeysItemsListView.ItemsSource = VirtualKeysListViewMappingItems; SaveButton.IsEnabled = true; AddNewItemButton.IsEnabled = true; AddNewVirtualKeyButton.IsEnabled = true; }
public void DerivedCollectionsShouldFollowBaseCollection() { var input = new[] {"Foo", "Bar", "Baz", "Bamf"}; var fixture = new ReactiveCollection<TestFixture>( input.Select(x => new TestFixture() { IsOnlyOneWord = x })); var output = fixture.CreateDerivedCollection(new Func<TestFixture, string>(x => x.IsOnlyOneWord)); input.AssertAreEqual(output); fixture.Add(new TestFixture() { IsOnlyOneWord = "Hello" }); Assert.Equal(5, output.Count); Assert.Equal(output[4], "Hello"); fixture.RemoveAt(4); Assert.Equal(4, output.Count); fixture[1] = new TestFixture() { IsOnlyOneWord = "Goodbye" }; Assert.Equal(4, output.Count); Assert.Equal(output[1], "Goodbye"); fixture.Clear(); Assert.Equal(0, output.Count); }
public void CollectionsShouldntShareSubscriptions() { var fixture1 = new ReactiveCollection<TestFixture>() { ChangeTrackingEnabled = true }; var fixture2 = new ReactiveCollection<TestFixture>() { ChangeTrackingEnabled = true }; var item1 = new TestFixture() { IsOnlyOneWord = "Foo" }; var output1 = new List<Tuple<TestFixture, string>>(); var output2 = new List<Tuple<TestFixture, string>>(); fixture1.ItemChanged.Subscribe(x => { output1.Add(new Tuple<TestFixture,string>((TestFixture)x.Sender, x.PropertyName)); }); fixture2.ItemChanged.Subscribe(x => { output2.Add(new Tuple<TestFixture,string>((TestFixture)x.Sender, x.PropertyName)); }); fixture1.Add(item1); fixture1.Add(item1); fixture2.Add(item1); fixture2.Add(item1); item1.IsOnlyOneWord = "Bar"; Assert.Equal(1, output1.Count); Assert.Equal(1, output2.Count); fixture2.RemoveAt(0); item1.IsOnlyOneWord = "Baz"; Assert.Equal(2, output1.Count); Assert.Equal(2, output2.Count); }
public PullRequestViewModel(IApplicationService applicationService, IMarkdownService markdownService, IShareService shareService) { _applicationService = applicationService; _markdownService = markdownService; Comments = new ReactiveCollection<IssueCommentModel>(); Events = new ReactiveCollection<IssueEventModel>(); MergeCommand = new ReactiveCommand(this.WhenAnyValue(x => x.PullRequest, x => x != null && x.Merged.HasValue && !x.Merged.Value && x.Mergable.HasValue && x.Mergable.Value)); MergeCommand.RegisterAsyncTask(async t => { try { var response = await _applicationService.Client.ExecuteAsync(_applicationService.Client.Users[RepositoryOwner].Repositories[RepositoryName].PullRequests[PullRequestId].Merge()); if (!response.Data.Merged) throw new Exception(response.Data.Message); var pullRequest = _applicationService.Client.Users[RepositoryOwner].Repositories[RepositoryName].PullRequests[PullRequestId].Get(); await this.RequestModel(pullRequest, true, r => PullRequest = r.Data); } catch (Exception e) { throw new Exception("Unable to Merge: " + e.Message, e); } }); ToggleStateCommand = new ReactiveCommand(this.WhenAnyValue(x => x.PullRequest, x => x != null)); ToggleStateCommand.RegisterAsyncTask(async t => { var close = string.Equals(PullRequest.State, "open", StringComparison.OrdinalIgnoreCase); try { var data = await _applicationService.Client.ExecuteAsync( _applicationService.Client.Users[RepositoryOwner].Repositories[RepositoryName].PullRequests[PullRequestId].UpdateState(close ? "closed" : "open")); PullRequest = data.Data; } catch (Exception e) { throw new Exception("Unable to " + (close ? "close" : "open") + " the item. " + e.Message, e); } }); GoToCommitsCommand = new ReactiveCommand(); GoToCommitsCommand.Subscribe(_ => { var vm = CreateViewModel<PullRequestCommitsViewModel>(); vm.RepositoryOwner = RepositoryOwner; vm.RepositoryName = RepositoryName; vm.PullRequestId = PullRequestId; ShowViewModel(vm); }); GoToFilesCommand = new ReactiveCommand(); GoToFilesCommand.Subscribe(_ => { var vm = CreateViewModel<PullRequestFilesViewModel>(); vm.Username = RepositoryOwner; vm.Repository = RepositoryName; vm.PullRequestId = PullRequestId; ShowViewModel(vm); }); ShareCommand = new ReactiveCommand(this.WhenAnyValue(x => x.PullRequest, x => x != null && !string.IsNullOrEmpty(x.HtmlUrl))); ShareCommand.Subscribe(_ => shareService.ShareUrl(PullRequest.HtmlUrl)); GoToEditCommand = new ReactiveCommand(); GoToEditCommand.Subscribe(_ => { var vm = CreateViewModel<IssueEditViewModel>(); vm.RepositoryOwner = RepositoryOwner; vm.RepositoryName = RepositoryName; vm.Id = PullRequestId; vm.Issue = Issue; vm.WhenAnyValue(x => x.Issue).Skip(1).Subscribe(x => Issue = x); ShowViewModel(vm); }); GoToLabelsCommand = new ReactiveCommand(this.WhenAnyValue(x => x.Issue, x => x != null)); GoToLabelsCommand.Subscribe(_ => { var vm = CreateViewModel<IssueLabelsViewModel>(); vm.RepositoryOwner = RepositoryOwner; vm.RepositoryName = RepositoryName; vm.IssueId = PullRequestId; vm.SaveOnSelect = true; vm.SelectedLabels.Reset(Issue.Labels); vm.WhenAnyValue(x => x.Labels).Skip(1).Subscribe(x => { Issue.Labels = x.ToList(); this.RaisePropertyChanged("Issue"); }); ShowViewModel(vm); }); GoToMilestoneCommand = new ReactiveCommand(this.WhenAnyValue(x => x.Issue, x => x != null)); GoToMilestoneCommand.Subscribe(_ => { var vm = CreateViewModel<IssueMilestonesViewModel>(); vm.RepositoryOwner = RepositoryOwner; vm.RepositoryName = RepositoryName; vm.IssueId = PullRequestId; vm.SaveOnSelect = true; vm.SelectedMilestone = Issue.Milestone; vm.WhenAnyValue(x => x.SelectedMilestone).Skip(1).Subscribe(x => { Issue.Milestone = x; this.RaisePropertyChanged("Issue"); }); ShowViewModel(vm); }); GoToAssigneeCommand = new ReactiveCommand(this.WhenAnyValue(x => x.Issue, x => x != null)); GoToAssigneeCommand.Subscribe(_ => { var vm = CreateViewModel<IssueAssignedToViewModel>(); vm.RepositoryOwner = RepositoryOwner; vm.RepositoryName = RepositoryName; vm.IssueId = PullRequestId; vm.SaveOnSelect = true; vm.SelectedUser = Issue.Assignee; vm.WhenAnyValue(x => x.SelectedUser).Skip(1).Subscribe(x => { Issue.Assignee = x; this.RaisePropertyChanged("Issue"); }); ShowViewModel(vm); }); GoToAddCommentCommand = new ReactiveCommand(); GoToAddCommentCommand.Subscribe(_ => { var vm = CreateViewModel<CommentViewModel>(); vm.SaveCommand.RegisterAsyncTask(async t => { var req = _applicationService.Client.Users[RepositoryOwner] .Repositories[RepositoryName].Issues[PullRequestId].CreateComment(vm.Comment); var comment = await _applicationService.Client.ExecuteAsync(req); Comments.Add(comment.Data); vm.DismissCommand.ExecuteIfCan(); }); }); LoadCommand.RegisterAsyncTask(t => { var forceCacheInvalidation = t as bool?; var pullRequest = _applicationService.Client.Users[RepositoryOwner].Repositories[RepositoryName].PullRequests[PullRequestId].Get(); var t1 = this.RequestModel(pullRequest, forceCacheInvalidation, response => PullRequest = response.Data); Events.SimpleCollectionLoad(_applicationService.Client.Users[RepositoryOwner].Repositories[RepositoryName].Issues[PullRequestId].GetEvents(), forceCacheInvalidation).FireAndForget(); Comments.SimpleCollectionLoad(_applicationService.Client.Users[RepositoryOwner].Repositories[RepositoryName].Issues[PullRequestId].GetComments(), forceCacheInvalidation).FireAndForget(); this.RequestModel(_applicationService.Client.Users[RepositoryOwner].Repositories[RepositoryName].Issues[PullRequestId].Get(), forceCacheInvalidation, response => Issue = response.Data).FireAndForget(); return t1; }); }
private void LoadSettings() { var settings = SettingsRepository.Load(SerializationId); if (settings == null) return; ColumnSettings = new ReactiveCollection<ColumnSettingsViewModel>(); foreach (var columnSettings in settings.ColumnSettings) { ColumnSettings.Add(new ColumnSettingsViewModel(columnSettings)); } ColumnSort = settings.ColumnSort; }
private void FillSizePrices() { SizePrices = new ReactiveCollection<SizePriceClass>(); System.Linq.IQueryable<LitTravData.Model.ItemSize> tmpTable; tmpTable = (from isz in context.ItemSizes where isz.Sku == SKU select isz); if (tmpTable.Count() == 0) { foreach (Size sz in SizeOptions) { SizePriceClass isc = new SizePriceClass(sz.SizeVal, ""); SizePrices.Add(isc); } } else { foreach (ItemSize isz in tmpTable) { SizePriceClass isc = new SizePriceClass(isz.SizeVal, isz.Price.ToString()); SizePrices.Add(isc); } } }
public IssueViewModel(IApplicationService applicationService, IShareService shareService) { _applicationService = applicationService; Comments = new ReactiveCollection<IssueCommentModel>(); Events = new ReactiveCollection<IssueEventModel>(); var issuePresenceObservable = this.WhenAnyValue(x => x.Issue, x => x != null); ShareCommand = new ReactiveCommand(this.WhenAnyValue(x => x.Issue, x => x != null && !string.IsNullOrEmpty(x.HtmlUrl))); ShareCommand.Subscribe(_ => shareService.ShareUrl(Issue.HtmlUrl)); AddCommentCommand = new ReactiveCommand(); AddCommentCommand.Subscribe(_ => { var vm = CreateViewModel<CommentViewModel>(); vm.SaveCommand.RegisterAsyncTask(async t => { var issue = _applicationService.Client.Users[RepositoryOwner].Repositories[RepositoryName].Issues[IssueId]; var comment = await _applicationService.Client.ExecuteAsync(issue.CreateComment(vm.Comment)); Comments.Add(comment.Data); vm.DismissCommand.ExecuteIfCan(); }); ShowViewModel(vm); }); ToggleStateCommand = new ReactiveCommand(issuePresenceObservable); ToggleStateCommand.RegisterAsyncTask(async t => { var close = string.Equals(Issue.State, "open", StringComparison.OrdinalIgnoreCase); try { var issue = _applicationService.Client.Users[RepositoryOwner].Repositories[RepositoryName].Issues[Issue.Number]; var data = await _applicationService.Client.ExecuteAsync(issue.UpdateState(close ? "closed" : "open")); Issue = data.Data; } catch (Exception e) { throw new Exception("Unable to " + (close ? "close" : "open") + " the item. " + e.Message, e); } }); GoToEditCommand = new ReactiveCommand(issuePresenceObservable); GoToEditCommand.Subscribe(_ => { var vm = CreateViewModel<IssueEditViewModel>(); vm.RepositoryOwner = RepositoryOwner; vm.RepositoryName = RepositoryName; vm.Id = IssueId; vm.Issue = Issue; vm.WhenAnyValue(x => x.Issue).Skip(1).Subscribe(x => Issue = x); ShowViewModel(vm); }); GoToAssigneeCommand = new ReactiveCommand(issuePresenceObservable); GoToAssigneeCommand.Subscribe(_ => { var vm = CreateViewModel<IssueAssignedToViewModel>(); vm.SaveOnSelect = true; vm.RepositoryOwner = RepositoryOwner; vm.RepositoryName = RepositoryName; vm.IssueId = IssueId; vm.SelectedUser = Issue.Assignee; vm.WhenAnyValue(x => x.SelectedUser).Subscribe(x => { Issue.Assignee = x; this.RaisePropertyChanged("Issue"); }); ShowViewModel(vm); }); GoToLabelsCommand = new ReactiveCommand(issuePresenceObservable); GoToLabelsCommand.Subscribe(_ => { var vm = CreateViewModel<IssueLabelsViewModel>(); vm.SaveOnSelect = true; vm.RepositoryOwner = RepositoryOwner; vm.RepositoryName = RepositoryName; vm.IssueId = IssueId; vm.SelectedLabels.Reset(Issue.Labels); vm.WhenAnyValue(x => x.SelectedLabels).Subscribe(x => { Issue.Labels = x.ToList(); this.RaisePropertyChanged("Issue"); }); ShowViewModel(vm); }); GoToMilestoneCommand = new ReactiveCommand(issuePresenceObservable); GoToMilestoneCommand.Subscribe(_ => { var vm = CreateViewModel<IssueMilestonesViewModel>(); vm.SaveOnSelect = true; vm.RepositoryOwner = RepositoryOwner; vm.RepositoryName = RepositoryName; vm.IssueId = IssueId; vm.SelectedMilestone = Issue.Milestone; vm.WhenAnyValue(x => x.SelectedMilestone).Subscribe(x => { Issue.Milestone = x; this.RaisePropertyChanged("Issue"); }); ShowViewModel(vm); }); LoadCommand.RegisterAsyncTask(t => { var forceCacheInvalidation = t as bool?; var issue = _applicationService.Client.Users[RepositoryOwner].Repositories[RepositoryName].Issues[IssueId]; var t1 = this.RequestModel(issue.Get(), forceCacheInvalidation, response => Issue = response.Data); Comments.SimpleCollectionLoad(issue.GetComments(), forceCacheInvalidation).FireAndForget(); Events.SimpleCollectionLoad(issue.GetEvents(), forceCacheInvalidation).FireAndForget(); return t1; }); }
public GridSettingsViewModel(ColumnManager cm) { Settings = new ReactiveCollection<ColumnSettingsViewModel>(); SettingsView = (CollectionView)CollectionViewSource.GetDefaultView(Settings); SettingsView.SortDescriptions.Add(new SortDescription {PropertyName = "Order", Direction = ListSortDirection.Ascending}); foreach (var csvm in cm.ColumnSettings) Settings.Add(csvm.Copy()); }