using System.Collections.ObjectModel; using System.Reactive.Disposables; using System.Reactive.Linq; using DynamicData; using ReactiveUI; using ReactiveUI.SourceGenerators; using Splat; using StarsAssistant.Model; using StarsAssistant.Services; namespace StarsAssistant.ViewModels; public partial class BuColViewModel : ViewModelBase { private readonly ReadOnlyObservableCollection _playerPlanetsView; public ReadOnlyObservableCollection PlayerPlanets => _playerPlanetsView; [Reactive] private PlayerPlanetViewModel? _selectedPlanet; private string? _lastSelectedPlanetName; public BuColViewModel() { var planetManager = Locator.Current.GetService()!; planetManager.PlayerPlanetsSource .ObserveOn(RxApp.MainThreadScheduler) .Bind(out _playerPlanetsView) .DisposeMany() .Subscribe(); this.WhenAnyValue(x => x.SelectedPlanet) .Subscribe(planet => _lastSelectedPlanetName = planet?.Name); this.WhenActivated((CompositeDisposable disposables) => { planetManager.PlanetsReloaded .ObserveOn(RxApp.MainThreadScheduler) .Subscribe(_ => RestoreSelection()) .DisposeWith(disposables); }); } private void RestoreSelection() { if (_lastSelectedPlanetName != null) { SelectedPlanet = PlayerPlanets.FirstOrDefault(p => p.Name == _lastSelectedPlanetName); } } }