Skip to content

Instantly share code, notes, and snippets.

@technocidal
Created June 20, 2023 18:44
Show Gist options
  • Save technocidal/87e18e043bc8d11b0b0ea40cedf60126 to your computer and use it in GitHub Desktop.
Save technocidal/87e18e043bc8d11b0b0ea40cedf60126 to your computer and use it in GitHub Desktop.
import SwiftUI
import Combine
import PlaygroundSupport
class SomeOtherObject: ObservableObject {
var cancellable: AnyCancellable? = nil
@Published var someValue = ""
init() {
self.cancellable = Timer.publish(every: 1, on: RunLoop.main, in: .default)
.autoconnect()
.sink { [weak self] _ in
print("I'em still here")
self?.someValue += "."
}
}
}
struct SomeView: View {
@StateObject var otherObj = SomeOtherObject()
@State var task: Task<(), Never>?
var body: some View {
Text("Hello, world!")
.onReceive(otherObj.$someValue, perform: { _ in
task?.cancel()
task = Task {
// Do some sort of work here
print("Do work")
if Task.isCancelled { return }
// Do some more work, update UI…
}
})
}
}
PlaygroundPage.current.setLiveView(SomeView())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment