From ecad02b74a9b1e4879a93d3da99918b9146ca6ac Mon Sep 17 00:00:00 2001 From: Jacob Hearst Date: Wed, 17 Aug 2022 07:45:06 -0500 Subject: [PATCH] Wrap search in scheduler --- .../Components/SearchView/SearchView.swift | 4 +--- .../SearchView/SearchViewModel.swift | 23 ++++++++++++++++--- .../MTGWizard.xcdatamodel/contents | 12 ++++++++++ 3 files changed, 33 insertions(+), 6 deletions(-) create mode 100644 MTGWizard/CoreData/MTGWizard.xcdatamodeld/MTGWizard.xcdatamodel/contents diff --git a/MTGWizard/Components/SearchView/SearchView.swift b/MTGWizard/Components/SearchView/SearchView.swift index 5ee1129..bd07768 100644 --- a/MTGWizard/Components/SearchView/SearchView.swift +++ b/MTGWizard/Components/SearchView/SearchView.swift @@ -47,8 +47,6 @@ struct SearchView: View { } func handleSubmit() { - Task { - await viewModel.search() - } + viewModel.scheduleSearch() } } diff --git a/MTGWizard/Components/SearchView/SearchViewModel.swift b/MTGWizard/Components/SearchView/SearchViewModel.swift index b42e324..d35f690 100644 --- a/MTGWizard/Components/SearchView/SearchViewModel.swift +++ b/MTGWizard/Components/SearchView/SearchViewModel.swift @@ -16,6 +16,7 @@ final class SearchViewModel: ObservableObject, SearchPersistable { private var storageLocation: StorageLocation private var debounceTimer: Timer? private var pageNumber = 1 + private var task: Task? @AppStorage("HideAlchemy") var hideAlchemy = false @AppStorage("DefaultFormat") var defaultFormat: Format? @@ -37,7 +38,7 @@ final class SearchViewModel: ObservableObject, SearchPersistable { @Published var showFilters = false { didSet { guard !showFilters else { return } - Task { await search() } + scheduleSearch() } } @@ -53,14 +54,22 @@ final class SearchViewModel: ObservableObject, SearchPersistable { self.searchText = state.searchTerm self.filters = state.filters - Task { await search() } + scheduleSearch() } // MARK: Search func debounceSearch() { debounceTimer?.invalidate() debounceTimer = Timer.scheduledTimer(withTimeInterval: 0.5, repeats: false) { _ in - Task { await self.search() } + self.scheduleSearch() + } + } + + func scheduleSearch() { + debounceTimer?.invalidate() + task?.cancel() + task = Task { + await search() } } @@ -144,4 +153,12 @@ final class SearchViewModel: ObservableObject, SearchPersistable { isLoadingMore = false } + + deinit { + // TODO: Is this necessary? + debounceTimer?.invalidate() + debounceTimer = nil + task?.cancel() + task = nil + } } diff --git a/MTGWizard/CoreData/MTGWizard.xcdatamodeld/MTGWizard.xcdatamodel/contents b/MTGWizard/CoreData/MTGWizard.xcdatamodeld/MTGWizard.xcdatamodel/contents new file mode 100644 index 0000000..e296d1d --- /dev/null +++ b/MTGWizard/CoreData/MTGWizard.xcdatamodeld/MTGWizard.xcdatamodel/contents @@ -0,0 +1,12 @@ + + + + + + + + + + + + \ No newline at end of file