Skip to content

Instantly share code, notes, and snippets.

@VAnsimov
Last active October 28, 2023 03:24
Show Gist options
  • Save VAnsimov/1bc67881ff61d6110c5122568918b5eb to your computer and use it in GitHub Desktop.
Save VAnsimov/1bc67881ff61d6110c5122568918b5eb to your computer and use it in GitHub Desktop.
BackgroundSerialPersistence
import Foundation
import SwiftData
/// ```swift
/// // One operation one instance of BackgroundSerialPersistenceActor class
/// let actor = BackgroundSerialPersistenceActor<MyModel>(container: modelContainer)
///
/// Task {
/// let data = try? await actor.fetchData()
/// }
/// ```
@available(iOS 17, *)
public actor BackgroundSerialPersistenceActor<T: PersistentModel>: ModelActor {
public let modelContainer: ModelContainer
public let modelExecutor: any ModelExecutor
private var context: ModelContext { modelExecutor.modelContext }
public init(container: ModelContainer) {
self.modelContainer = container
let context = ModelContext(modelContainer)
modelExecutor = DefaultSerialModelExecutor(modelContext: context)
}
public func fetchData(descriptor: FetchDescriptor<T>) throws -> [T] {
let list: [T] = try context.fetch(descriptor)
return list
}
public func fetchData(predicate: Predicate<T>? = nil) throws -> [T] {
let fetchDescriptor = FetchDescriptor<T>(predicate: predicate)
let list: [T] = try context.fetch(fetchDescriptor)
return list
}
public func save(data: T) throws {
context.insert(data)
try context.save()
}
public func remove(predicate: Predicate<T>? = nil) throws {
try context.delete(model: T.self, where: predicate)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment