Skip to content

Instantly share code, notes, and snippets.

View SmartJSONEditor's full-sized avatar

Jan Kubny SmartJSONEditor

View GitHub Profile
/// Requiered to use as @StateObject in a View for proper ownership.
extension ViewModel: ObservableObject {}
@Observable
class ViewModel {
/// Details
}
struct ContentView {
/// @Observed object
struct ContentWrapperView: View {
@State var redrawTrigger: Bool = false
let timer = Timer.publish(every: 1, on: .main, in: .common).autoconnect()
var body: some View {
VStack {
Text("Redraw triggered with bool: \(redrawTrigger)")
ContentView() /// On every redraw, new viewModel instance is allocated in ContentView
}
@Observable
class ViewModel {
public var title: String
deinit {
print("deinit ViewModel")
}
init(title: String) {
class ViewModel: ObservableObject {
@Published public var title: String
deinit {
print("deinit ViewModel")
}
init(title: String) {
self.title = title
// AFTER
@main
struct BookReaderApp: App {
/// Object is allocated in a global context.
@State private var library = Library()
var body: some Scene {
WindowGroup {
LibraryView()
.environment(library)
@SmartJSONEditor
SmartJSONEditor / gist:33d796e81554205fd491b6449376c426
Last active March 31, 2024 05:38
Observation withObservationTracking as Combine publisher
import Combine
import Foundation
import Observation
// A: Using specific class
/// Class that wraps withObservationTracking function into a Combine compatible continuos stream publisher
public class ObservationTracker<O: Observable & AnyObject, T> {
/// Subscribe to a publisher.
public var valuePublisher: AnyPublisher<T, Never> {