Skip to content

Instantly share code, notes, and snippets.

@habibg1232191
Last active August 13, 2022 10:15
Show Gist options
  • Select an option

  • Save habibg1232191/51d0d4465c1b01b558aee4acd8473519 to your computer and use it in GitHub Desktop.

Select an option

Save habibg1232191/51d0d4465c1b01b558aee4acd8473519 to your computer and use it in GitHub Desktop.
public class MainWindowViewModel : ViewModelBase
{
private CancellationToken _cancellationToken;
private CancellationTokenSource _cancellationTokenSource = new();
private int _pageIndex = 1;
private ObservableCollection<IWallpaperInfo> _wallpapers = new();
private string _searchString = "";
public ObservableCollection<IWallpaperInfo> Wallpapers
{
get => _wallpapers;
private set => this.RaiseAndSetIfChanged(ref _wallpapers, value);
}
public string SearchString
{
get => _searchString;
set => this.RaiseAndSetIfChanged(ref _searchString, value);
}
public MainWindowViewModel()
{
CloseLastTask();
this.WhenAnyValue(x => x.SearchString).Subscribe(OnSearchStringChanged);
}
public void VisibleChange()
{
IsVisible = !IsVisible;
}
private void OnSearchStringChanged(string newValue)
{
Dispatcher.UIThread.Post(TryLoadWallpapers);
}
private async void TryLoadWallpapers()
{
CloseLastTask();
if (!await InternetSession.IsInternetConnection() || _cancellationToken.IsCancellationRequested) return;
try
{
var addedWallpapers =
await WallpaperPluginService.SelectedPlugin.Search(SearchString, _pageIndex, _cancellationToken).WaitAsync(_cancellationToken);
_cancellationToken.ThrowIfCancellationRequested();
Wallpapers = new ObservableCollection<IWallpaperInfo>(addedWallpapers.ToList());
}
catch (OperationCanceledException e)
{
Console.WriteLine("Close Task");
// CloseLastTask();
// TryLoadWallpapers();
}
}
private void CloseLastTask()
{
_pageIndex = 1;
_cancellationTokenSource.Cancel();
_cancellationTokenSource = new CancellationTokenSource();
_cancellationToken = _cancellationTokenSource.Token;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment