forked from pointfreeco/sqlite-data
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAnimations.swift
More file actions
84 lines (76 loc) · 2.01 KB
/
Animations.swift
File metadata and controls
84 lines (76 loc) · 2.01 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
import SQLiteData
import SwiftUI
struct AnimationsCaseStudy: SwiftUICaseStudy {
let readMe = """
This demonstrates how to animate fetching data from the database, or when data changes in \
the database. Simply provide the `animation` argument to `@FetchAll` (or the other querying \
tools, such as `@Fetch` and `@FetchOne`).
This is analogous to how animations work in SwiftData in which one provides an `animation` \
argument to the `@Query` macro.
"""
let caseStudyTitle = "Animations"
@FetchAll(Fact.order { $0.id.desc() }, animation: .default)
private var facts
@Dependency(\.defaultDatabase) var database
var body: some View {
List {
ForEach(facts) { fact in
Text(fact.body)
}
}
.task {
do {
var number = 0
while true {
try await Task.sleep(for: .seconds(1))
number += 1
let fact = try await String(
decoding: URLSession.shared
.data(from: URL(string: "http://numberapi.com/\(number)")!).0,
as: UTF8.self
)
try await database.write { db in
try Fact.insert {
Fact.Draft(body: fact)
}
.execute(db)
}
}
} catch {}
}
}
}
@Table
nonisolated private struct Fact: Identifiable {
let id: Int
var body: String
}
extension DatabaseWriter where Self == DatabaseQueue {
static var animationDatabase: Self {
let databaseQueue = try! DatabaseQueue()
var migrator = DatabaseMigrator()
migrator.registerMigration("Create 'facts' table") { db in
try #sql(
"""
CREATE TABLE "facts" (
"id" INTEGER PRIMARY KEY AUTOINCREMENT,
"body" TEXT NOT NULL
) STRICT
"""
)
.execute(db)
}
try! migrator.migrate(databaseQueue)
return databaseQueue
}
}
#Preview {
let _ = prepareDependencies {
$0.defaultDatabase = .animationDatabase
}
NavigationStack {
CaseStudyView {
AnimationsCaseStudy()
}
}
}