Skip to content
This repository has been archived by the owner on Aug 13, 2024. It is now read-only.

Commit

Permalink
fix: prevent update loop when using ObservableObjects (fixes #10)
Browse files Browse the repository at this point in the history
  • Loading branch information
thislooksfun committed Nov 25, 2020
1 parent e23cc7e commit 3a20859
Show file tree
Hide file tree
Showing 4 changed files with 45 additions and 0 deletions.
2 changes: 2 additions & 0 deletions Sources/SwiftlySearch/SwiftlySearch.swift
Original file line number Diff line number Diff line change
Expand Up @@ -107,6 +107,8 @@ struct SearchBar<ResultContent: View>: UIViewControllerRepresentable {
// MARK: - UISearchResultsUpdating
func updateSearchResults(for searchController: UISearchController) {
guard let text = searchController.searchBar.text else { return }
// Make sure the text has actually changed (workaround for #10).
guard text != self.text else { return }
DispatchQueue.main.async {
self.text = text
}
Expand Down
4 changes: 4 additions & 0 deletions Tests/TestApp/ContentView.swift
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,10 @@ struct ContentView: View {
NavigationLink(destination: CallbackUpdateTest()) {
Text("Callback Update")
}

NavigationLink(destination: ObservablePublishedTest()) {
Text("Observable Published")
}
}
.navigationBarTitle("Tests")
}
Expand Down
22 changes: 22 additions & 0 deletions Tests/TestApp/TestViews/ObservablePublishedTest.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import SwiftUI

class ObservablePublishedModel: ObservableObject {
@Published var searchText = ""
}

struct ObservablePublishedTest: View {
@ObservedObject var viewModel = ObservablePublishedModel()

var body: some View {
List {
Text("foo")
}
.navigationBarSearch($viewModel.searchText)
}
}

struct ObservablePublishedTest_Previews: PreviewProvider {
static var previews: some View {
ObservablePublishedTest()
}
}
17 changes: 17 additions & 0 deletions Tests/UITests/ObservablePublishedTests.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
// I was unable to get this test to work, but I'm leaving it in as a reminder for the future.

//import XCTest
//
//class ObservablePublishedTests: UITest {
// func testObservablePublishedMetric() throws {
// selectTest("Observable Published")
//
// measure(metrics: [XCTCPUMetric(application: app)]) {
// app.children(matching: .any).firstMatch.slowSwipeDown(offset: 0.5, distance: 0.1)
//
// // Ensure the searchbar exists.
// let navBar = app.navigationBars.firstMatch
// XCTAssertTrue(navBar.children(matching: .searchField).firstMatch.exists, "Searchbar exists")
// }
// }
//}

0 comments on commit 3a20859

Please sign in to comment.