Suggestion: cancel previous task

This commit is contained in:
Thomas Ricouard 2023-03-04 09:55:17 +01:00
parent 761c8ed3be
commit 1466d9690a

View file

@ -126,7 +126,9 @@ public class StatusEditorViewModel: NSObject, ObservableObject {
} }
private var mentionString: String? private var mentionString: String?
private var uploadTask: Task<Void, Never>? private var uploadTask: Task<Void, Never>?
private var suggestedTask: Task<Void, Never>?
init(mode: Mode) { init(mode: Mode) {
self.mode = mode self.mode = mode
@ -433,7 +435,8 @@ public class StatusEditorViewModel: NSObject, ObservableObject {
private func loadAutoCompleteResults(query: String) { private func loadAutoCompleteResults(query: String) {
guard let client, query.utf8.count > 1 else { return } guard let client, query.utf8.count > 1 else { return }
var query = query var query = query
Task { suggestedTask?.cancel()
suggestedTask = Task {
do { do {
var results: SearchResults? var results: SearchResults?
switch query.first { switch query.first {
@ -444,6 +447,9 @@ public class StatusEditorViewModel: NSObject, ObservableObject {
offset: 0, offset: 0,
following: nil), following: nil),
forceVersion: .v2) forceVersion: .v2)
guard !Task.isCancelled else {
return
}
withAnimation { withAnimation {
tagsSuggestions = results?.hashtags.sorted(by: { $0.totalUses > $1.totalUses }) ?? [] tagsSuggestions = results?.hashtags.sorted(by: { $0.totalUses > $1.totalUses }) ?? []
} }
@ -454,6 +460,9 @@ public class StatusEditorViewModel: NSObject, ObservableObject {
offset: 0, offset: 0,
following: true), following: true),
forceVersion: .v2) forceVersion: .v2)
guard !Task.isCancelled else {
return
}
withAnimation { withAnimation {
mentionsSuggestions = results?.accounts ?? [] mentionsSuggestions = results?.accounts ?? []
} }