-
Notifications
You must be signed in to change notification settings - Fork 85
/
Copy pathCombinedProvider.swift
80 lines (65 loc) · 2.49 KB
/
CombinedProvider.swift
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
//
// CombinedProvider.swift
// LockdownFirewallWidgetExtension
//
// Created by Oleg Dreyman on 28.09.2020.
// Copyright © 2020 Confirmed Inc. All rights reserved.
//
import Foundation
import WidgetKit
struct CombinedProvider<Main: TimelineProvider, Supplemental: TimelineProvider>: TimelineProvider {
let main: Main
let supplemental: Supplemental
struct Entry: TimelineEntry {
var main: Main.Entry
var supplemental: Supplemental.Entry
var date: Date {
return min(main.date, supplemental.date)
}
}
func placeholder(in context: Context) -> Entry {
let leftPlaceholder = main.placeholder(in: context)
let rightPlaceholder = supplemental.placeholder(in: context)
return Entry(main: leftPlaceholder, supplemental: rightPlaceholder)
}
func getSnapshot(in context: Context, completion: @escaping (Entry) -> Void) {
var leftSnapshot: Main.Entry?
var rightSnapshot: Supplemental.Entry?
let group = DispatchGroup()
group.enter()
main.getSnapshot(in: context) { (leftEntry) in
leftSnapshot = leftEntry
group.leave()
}
group.enter()
supplemental.getSnapshot(in: context) { (rightEntry) in
rightSnapshot = rightEntry
group.leave()
}
dispatchPrecondition(condition: .onQueue(.main))
group.notify(queue: .main) {
completion(Entry(main: leftSnapshot!, supplemental: rightSnapshot!))
}
}
func getTimeline(in context: Context, completion: @escaping (Timeline<Entry>) -> Void) {
var leftTimeline: Timeline<Main.Entry>?
var rightTimeline: Timeline<Supplemental.Entry>?
let group = DispatchGroup()
group.enter()
main.getTimeline(in: context) { (leftEntry) in
leftTimeline = leftEntry
group.leave()
}
group.enter()
supplemental.getTimeline(in: context) { (rightEntry) in
rightTimeline = rightEntry
group.leave()
}
dispatchPrecondition(condition: .onQueue(.main))
group.notify(queue: .main) {
let zippedEntries = zip(leftTimeline!.entries, rightTimeline!.entries)
let timeline = Timeline<Entry>(entries: zippedEntries.map({ Entry.init(main: $0, supplemental: $1) }), policy: leftTimeline!.policy)
completion(timeline)
}
}
}