Skip to content

Instantly share code, notes, and snippets.

@gtokman
Last active March 28, 2021 18:50
Show Gist options
  • Select an option

  • Save gtokman/94ad17a616c1908715c1253c67ac9fcf to your computer and use it in GitHub Desktop.

Select an option

Save gtokman/94ad17a616c1908715c1253c67ac9fcf to your computer and use it in GitHub Desktop.
CurrentValueSubject - combine
// Create a new search subject with a default value
let searchSubject = CurrentValueSubject<String, Never>("")
// Subscribe to updates
searchSubject
.debounce(for: 0.3, scheduler: DispatchQueue.main)
.map(searchBook(for:))
.flatMap {$0.map(\.author)}
.subscribe(on: DispatchQueue.main)
.sink { author in
print("Book author from API:", author)
}
.store(in: &cancellables)
print(searchSubject.value) // empty string
// Send new search i.e. search bar
searchSubject.send("th") // too short of time we debounce
DispatchQueue.main.asyncAfter(deadline: .now() + 0.4) {
searchSubject.send("the 4 hour") // debounce
searchSubject.send("the 4 hour work week") // search
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment