-
Notifications
You must be signed in to change notification settings - Fork 2.2k
Expand file tree
/
Copy pathCombine.swift
More file actions
2303 lines (2095 loc) · 113 KB
/
Copy pathCombine.swift
File metadata and controls
2303 lines (2095 loc) · 113 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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
////////////////////////////////////////////////////////////////////////////
//
// Copyright 2020 Realm Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
////////////////////////////////////////////////////////////////////////////
#if !(os(iOS) && (arch(i386) || arch(arm)))
import Combine
import Realm
import Realm.Private
// MARK: - Identifiable
/// A protocol which defines a default identity for Realm Objects
///
/// Declaring your Object subclass as conforming to this protocol will supply
/// a default implementation for `Identifiable`'s `id` which works for Realm
/// Objects:
///
/// // Automatically conforms to `Identifiable`
/// class MyObjectType: Object, ObjectKeyIdentifiable {
/// // ...
/// }
///
/// You can also manually conform to `Identifiable` if you wish, but note that
/// using the object's memory address does *not* work for managed objects.
@available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)
public protocol ObjectKeyIdentifiable: Identifiable {
/// The stable identity of the entity associated with `self`.
var id: UInt64 { get }
}
/// :nodoc:
@available(*, deprecated, renamed: "ObjectKeyIdentifiable")
@available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)
public typealias ObjectKeyIdentifable = ObjectKeyIdentifiable
@available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)
extension ObjectKeyIdentifiable where Self: ObjectBase {
/// A stable identifier for this object. For managed Realm objects, this
/// value will be the same for all object instances which refer to the same
/// object (i.e. for which `Object.isSameObject(as:)` returns true).
public var id: UInt64 {
RLMObjectBaseGetCombineId(self)
}
}
/// :nodoc:
@available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)
extension ObjectKeyIdentifiable where Self: ProjectionObservable {
/// A stable identifier for this projection.
public var id: UInt64 {
RLMObjectBaseGetCombineId(rootObject)
}
}
// MARK: - Combine
/// A type which can be passed to `valuePublisher()` or `changesetPublisher()`.
@available(OSX 10.15, watchOS 6.0, iOS 13.0, iOSApplicationExtension 13.0, OSXApplicationExtension 10.15, tvOS 13.0, *)
public protocol RealmSubscribable {
/// :nodoc:
func _observe<S>(_ keyPaths: [String]?, on queue: DispatchQueue?, _ subscriber: S)
-> NotificationToken where S: Subscriber, S.Input == Self, S.Failure == Error
/// :nodoc:
func _observe<S>(_ keyPaths: [String]?, _ subscriber: S)
-> NotificationToken where S: Subscriber, S.Input == Void, S.Failure == Never
}
@available(OSX 10.15, watchOS 6.0, iOS 13.0, iOSApplicationExtension 13.0, OSXApplicationExtension 10.15, tvOS 13.0, *)
extension Publisher {
/// Freezes all Realm objects and collections emitted by the upstream publisher
///
/// Freezing a Realm object makes it no longer live-update when writes are
/// made to the Realm and makes it safe to pass freely between threads
/// without using `.threadSafeReference()`.
///
/// ```
/// // Get a publisher for a Results
/// let cancellable = myResults.publisher
/// // Convert to frozen Results
/// .freeze()
/// // Unlike live objects, frozen objects can be sent to a concurrent queue
/// .receive(on: DispatchQueue.global())
/// .sink { frozenResults in
/// // Do something with the frozen Results
/// }
/// ```
///
/// - returns: A publisher that publishes frozen copies of the objects which the upstream publisher publishes.
public func freeze<T>() -> Publishers.Map<Self, T> where Output: ThreadConfined, T == Output {
return map { $0.freeze() }
}
/// Freezes all Realm object changesets emitted by the upstream publisher.
///
/// Freezing a Realm object changeset makes the included object reference
/// no longer live-update when writes are made to the Realm and makes it
/// safe to pass freely between threads without using
/// `.threadSafeReference()`. It also guarantees that the frozen object
/// contained in the changset will always match the property changes, which
/// is not always the case when using thread-safe references.
///
/// ```
/// // Get a changeset publisher for an object
/// let cancellable = changesetPublisher(object)
/// // Convert to frozen changesets
/// .freeze()
/// // Unlike live objects, frozen objects can be sent to a concurrent queue
/// .receive(on: DispatchQueue.global())
/// .sink { changeset in
/// // Do something with the frozen changeset
/// }
/// ```
///
/// - returns: A publisher that publishes frozen copies of the changesets
/// which the upstream publisher publishes.
public func freeze<T: Object>() -> Publishers.Map<Self, ObjectChange<T>> where Output == ObjectChange<T> {
return map {
if case .change(let object, let properties) = $0 {
return .change(object.freeze(), properties)
}
return $0
}
}
/// Freezes all Realm collection changesets from the upstream publisher.
///
/// Freezing a Realm collection changeset makes the included collection
/// reference no longer live-update when writes are made to the Realm and
/// makes it safe to pass freely between threads without using
/// `.threadSafeReference()`. It also guarantees that the frozen collection
/// contained in the changset will always match the change information,
/// which is not always the case when using thread-safe references.
///
/// ```
/// // Get a changeset publisher for a collection
/// let cancellable = myList.changesetPublisher
/// // Convert to frozen changesets
/// .freeze()
/// // Unlike live objects, frozen objects can be sent to a concurrent queue
/// .receive(on: DispatchQueue.global())
/// .sink { changeset in
/// // Do something with the frozen changeset
/// }
/// ```
///
/// - returns: A publisher that publishes frozen copies of the changesets
/// which the upstream publisher publishes.
public func freeze<T: RealmCollection>()
-> Publishers.Map<Self, RealmCollectionChange<T>> where Output == RealmCollectionChange<T> {
return map {
switch $0 {
case .initial(let collection):
return .initial(collection.freeze())
case .update(let collection, deletions: let deletions, insertions: let insertions, modifications: let modifications):
return .update(collection.freeze(), deletions: deletions, insertions: insertions, modifications: modifications)
case .error(let error):
return .error(error)
}
}
}
/// Freezes all Realm collection changesets from the upstream publisher.
///
/// Freezing a Realm collection changeset makes the included collection
/// reference no longer live-update when writes are made to the Realm and
/// makes it safe to pass freely between threads without using
/// `.threadSafeReference()`. It also guarantees that the frozen collection
/// contained in the changset will always match the change information,
/// which is not always the case when using thread-safe references.
///
/// ```
/// // Get a changeset publisher for a collection
/// let cancellable = myMap.changesetPublisher
/// // Convert to frozen changesets
/// .freeze()
/// // Unlike live objects, frozen objects can be sent to a concurrent queue
/// .receive(on: DispatchQueue.global())
/// .sink { changeset in
/// // Do something with the frozen changeset
/// }
/// ```
///
/// - returns: A publisher that publishes frozen copies of the changesets
/// which the upstream publisher publishes.
public func freeze<T: RealmKeyedCollection>()
-> Publishers.Map<Self, RealmMapChange<T>> where Output == RealmMapChange<T> {
return map {
switch $0 {
case .initial(let collection):
return .initial(collection.freeze())
case .update(let collection, deletions: let deletions, insertions: let insertions, modifications: let modifications):
return .update(collection.freeze(), deletions: deletions, insertions: insertions, modifications: modifications)
case .error(let error):
return .error(error)
}
}
}
/// Freezes all Realm projection changesets emitted by the upstream publisher.
///
/// Freezing a Realm projection changeset makes the included projection reference
/// no longer live-update when writes are made to the Realm and makes it
/// safe to pass freely between threads without using
/// `.threadSafeReference()`. It also guarantees that the frozen projection
/// contained in the changset will always match the property changes, which
/// is not always the case when using thread-safe references.
///
/// ```
/// // Get a changeset publisher for an projection
/// let cancellable = changesetPublisher(projection)
/// // Convert to frozen changesets
/// .freeze()
/// // Unlike live projections, frozen projections can be sent to a concurrent queue
/// .receive(on: DispatchQueue.global())
/// .sink { changeset in
/// // Do something with the frozen changeset
/// }
/// ```
///
/// - returns: A publisher that publishes frozen copies of the changesets
/// which the upstream publisher publishes.
public func freeze<T: ProjectionObservable>()
-> Publishers.Map<Self, ObjectChange<T>> where Output == ObjectChange<T>, T: ThreadConfined {
return map {
if case .change(let projection, let properties) = $0 {
return .change(projection.freeze(), properties)
}
return $0
}
}
}
@available(OSX 10.15, watchOS 6.0, iOS 13.0, iOSApplicationExtension 13.0, OSXApplicationExtension 10.15, tvOS 13.0, *)
extension Publisher where Output: ThreadConfined {
/// Enables passing thread-confined objects to a different dispatch queue.
///
/// Each call to `receive(on:)` on a publisher which emits Realm
/// thread-confined objects must be proceeded by a call to
/// `.threadSafeReference()`.The returned publisher handles the required
/// logic to pass the thread-confined object to the new queue. Only serial
/// dispatch queues are supported and using other schedulers will result in
/// a fatal error.
///
/// For example, to subscribe on a background thread, do some work there,
/// then pass the object to the main thread you can do:
///
/// let cancellable = publisher(myObject)
/// .subscribe(on: DispatchQueue(label: "background queue")
/// .print()
/// .threadSafeReference()
/// .receive(on: DispatchQueue.main)
/// .sink { object in
/// // Do things with the object on the main thread
/// }
///
/// Calling this function on a publisher which emits frozen or unmanaged
/// objects is unneccesary but is allowed.
///
/// - returns: A publisher that supports `receive(on:)` for thread-confined objects.
public func threadSafeReference() -> RealmPublishers.MakeThreadSafe<Self> {
RealmPublishers.MakeThreadSafe(self)
}
}
@available(OSX 10.15, watchOS 6.0, iOS 13.0, iOSApplicationExtension 13.0, OSXApplicationExtension 10.15, tvOS 13.0, *)
extension Publisher {
/// Enables passing object changesets to a different dispatch queue.
///
/// Each call to `receive(on:)` on a publisher which emits Realm
/// thread-confined objects must be proceeded by a call to
/// `.threadSafeReference()`. The returned publisher handles the required
/// logic to pass the thread-confined object to the new queue. Only serial
/// dispatch queues are supported and using other schedulers will result in
/// a fatal error.
///
/// For example, to subscribe on a background thread, do some work there,
/// then pass the object changeset to the main thread you can do:
///
/// let cancellable = changesetPublisher(myObject)
/// .subscribe(on: DispatchQueue(label: "background queue")
/// .print()
/// .threadSafeReference()
/// .receive(on: DispatchQueue.main)
/// .sink { objectChange in
/// // Do things with the object on the main thread
/// }
///
/// - returns: A publisher that supports `receive(on:)` for thread-confined objects.
public func threadSafeReference<T: Object>()
-> RealmPublishers.MakeThreadSafeObjectChangeset<Self, T> where Output == ObjectChange<T> {
RealmPublishers.MakeThreadSafeObjectChangeset(self)
}
/// Enables passing projection changesets to a different dispatch queue.
///
/// Each call to `receive(on:)` on a publisher which emits Realm
/// thread-confined projection must be proceeded by a call to
/// `.threadSafeReference()`. The returned publisher handles the required
/// logic to pass the thread-confined projection to the new queue. Only serial
/// dispatch queues are supported and using other schedulers will result in
/// a fatal error.
///
/// For example, to subscribe on a background thread, do some work there,
/// then pass the projection changeset to the main thread you can do:
///
/// let cancellable = changesetPublisher(myProjection)
/// .subscribe(on: DispatchQueue(label: "background queue")
/// .print()
/// .threadSafeReference()
/// .receive(on: DispatchQueue.main)
/// .sink { projectionChange in
/// // Do things with the projection on the main thread
/// }
///
/// - returns: A publisher that supports `receive(on:)` for thread-confined objects.
public func threadSafeReference<T: ProjectionObservable>()
-> RealmPublishers.MakeThreadSafeProjectionChangeset<Self, T> where Output == ObjectChange<T>, T: ThreadConfined {
RealmPublishers.MakeThreadSafeProjectionChangeset(self)
}
/// Enables passing Realm collection changesets to a different dispatch queue.
///
/// Each call to `receive(on:)` on a publisher which emits Realm
/// thread-confined objects must be proceeded by a call to
/// `.threadSafeReference()`. The returned publisher handles the required
/// logic to pass the thread-confined object to the new queue. Only serial
/// dispatch queues are supported and using other schedulers will result in
/// a fatal error.
///
/// For example, to subscribe on a background thread, do some work there,
/// then pass the collection changeset to the main thread you can do:
///
/// let cancellable = myCollection.changesetPublisher
/// .subscribe(on: DispatchQueue(label: "background queue")
/// .print()
/// .threadSafeReference()
/// .receive(on: DispatchQueue.main)
/// .sink { collectionChange in
/// // Do things with the collection on the main thread
/// }
///
/// - returns: A publisher that supports `receive(on:)` for thread-confined objects.
public func threadSafeReference<T: RealmCollection>()
-> RealmPublishers.MakeThreadSafeCollectionChangeset<Self, T> where Output == RealmCollectionChange<T> {
RealmPublishers.MakeThreadSafeCollectionChangeset(self)
}
/// Enables passing Realm collection changesets to a different dispatch queue.
///
/// Each call to `receive(on:)` on a publisher which emits Realm
/// thread-confined objects must be proceeded by a call to
/// `.threadSafeReference()`. The returned publisher handles the required
/// logic to pass the thread-confined object to the new queue. Only serial
/// dispatch queues are supported and using other schedulers will result in
/// a fatal error.
///
/// For example, to subscribe on a background thread, do some work there,
/// then pass the collection changeset to the main thread you can do:
///
/// let cancellable = myCollection.changesetPublisher
/// .subscribe(on: DispatchQueue(label: "background queue")
/// .print()
/// .threadSafeReference()
/// .receive(on: DispatchQueue.main)
/// .sink { collectionChange in
/// // Do things with the collection on the main thread
/// }
///
/// - returns: A publisher that supports `receive(on:)` for thread-confined objects.
public func threadSafeReference<T: RealmKeyedCollection>()
-> RealmPublishers.MakeThreadSafeKeyedCollectionChangeset<Self, T> where Output == RealmMapChange<T> {
RealmPublishers.MakeThreadSafeKeyedCollectionChangeset(self)
}
}
@available(OSX 10.15, watchOS 6.0, iOS 13.0, iOSApplicationExtension 13.0, OSXApplicationExtension 10.15, tvOS 13.0, *)
extension RealmCollection where Self: RealmSubscribable {
/// A publisher that emits Void each time the collection changes.
///
/// Despite the name, this actually emits *after* the collection has changed.
public var objectWillChange: RealmPublishers.WillChange<Self> {
RealmPublishers.WillChange(self)
}
/// :nodoc:
@available(*, deprecated, renamed: "collectionPublisher")
public var publisher: RealmPublishers.Value<Self> {
RealmPublishers.Value(self)
}
/// A publisher that emits the collection each time the collection changes.
public var collectionPublisher: RealmPublishers.Value<Self> {
RealmPublishers.Value(self)
}
/// A publisher that emits the collection each time the collection changes on the given property keyPaths.
public func collectionPublisher(keyPaths: [String]?) -> RealmPublishers.Value<Self> {
return RealmPublishers.Value(self, keyPaths: keyPaths)
}
/// A publisher that emits a collection changeset each time the collection changes.
public var changesetPublisher: RealmPublishers.CollectionChangeset<Self> {
RealmPublishers.CollectionChangeset(self)
}
/// A publisher that emits a collection changeset each time the collection changes on the given property keyPaths.
public func changesetPublisher(keyPaths: [String]?) -> RealmPublishers.CollectionChangeset<Self> {
return RealmPublishers.CollectionChangeset(self, keyPaths: keyPaths)
}
}
@available(OSX 10.15, watchOS 6.0, iOS 13.0, iOSApplicationExtension 13.0, OSXApplicationExtension 10.15, tvOS 13.0, *)
extension RealmKeyedCollection where Self: RealmSubscribable {
/// A publisher that emits Void each time the collection changes.
///
/// Despite the name, this actually emits *after* the collection has changed.
public var objectWillChange: RealmPublishers.WillChange<Self> {
RealmPublishers.WillChange(self)
}
/// :nodoc:
@available(*, deprecated, renamed: "collectionPublisher")
public var publisher: RealmPublishers.Value<Self> {
RealmPublishers.Value(self)
}
/// A publisher that emits the collection each time the collection changes.
public var collectionPublisher: RealmPublishers.Value<Self> {
RealmPublishers.Value(self)
}
/// A publisher that emits the collection each time the collection changes on the given property keyPaths.
public func collectionPublisher(keyPaths: [String]?) -> RealmPublishers.Value<Self> {
return RealmPublishers.Value(self, keyPaths: keyPaths)
}
/// A publisher that emits a collection changeset each time the collection changes.
public var changesetPublisher: RealmPublishers.MapChangeset<Self> {
RealmPublishers.MapChangeset(self)
}
/// A publisher that emits a collection changeset each time the collection changes on the given property keyPaths.
public func changesetPublisher(keyPaths: [String]?) -> RealmPublishers.MapChangeset<Self> {
return RealmPublishers.MapChangeset(self, keyPaths: keyPaths)
}
}
/// Creates a publisher that emits the object each time the object changes.
///
/// - precondition: The object must be a managed object which has not been invalidated.
/// - parameter object: A managed object to observe.
/// - parameter keyPaths: The publisher emits changes on these property keyPaths. If `nil` the publisher emits changes for every property.
/// - returns: A publisher that emits the object each time it changes.
@available(OSX 10.15, watchOS 6.0, iOS 13.0, iOSApplicationExtension 13.0, OSXApplicationExtension 10.15, tvOS 13.0, *)
public func valuePublisher<T: Object>(_ object: T, keyPaths: [String]? = nil) -> RealmPublishers.Value<T> {
RealmPublishers.Value<T>(object, keyPaths: keyPaths)
}
/// Creates a publisher that emits the collection each time the collection changes.
///
/// - precondition: The collection must be a managed collection which has not been invalidated.
/// - parameter object: A managed collection to observe.
/// - parameter keyPaths: The publisher emits changes on these property keyPaths. If `nil` the publisher emits changes for every property.
/// - returns: A publisher that emits the collection each time it changes.
@available(OSX 10.15, watchOS 6.0, iOS 13.0, iOSApplicationExtension 13.0, OSXApplicationExtension 10.15, tvOS 13.0, *)
public func valuePublisher<T: RealmCollection>(_ collection: T, keyPaths: [String]? = nil) -> RealmPublishers.Value<T> {
RealmPublishers.Value<T>(collection, keyPaths: keyPaths)
}
/// Creates a publisher that emits the object each time the object changes.
///
/// - precondition: The object must be a managed object which has not been invalidated.
/// - parameter object: A managed object to observe.
/// - parameter keyPaths: The publisher emits changes on these property keyPaths. If `nil` the publisher emits changes for every property.
/// - returns: A publisher that emits the object each time it changes.
@available(OSX 10.15, watchOS 6.0, iOS 13.0, iOSApplicationExtension 13.0, OSXApplicationExtension 10.15, tvOS 13.0, *)
public func valuePublisher<T: ProjectionObservable>(_ projection: T, keyPaths: [String]? = nil) -> RealmPublishers.Value<T> {
RealmPublishers.Value<T>(projection, keyPaths: keyPaths)
}
/// Creates a publisher that emits an object changeset each time the object changes.
///
/// - precondition: The object must be a managed object which has not been invalidated.
/// - parameter object: A managed object to observe.
/// - parameter keyPaths: The publisher emits changes on these property keyPaths. If `nil` the publisher emits changes for every property.
/// - returns: A publisher that emits an object changeset each time the object changes.
@available(OSX 10.15, watchOS 6.0, iOS 13.0, iOSApplicationExtension 13.0, OSXApplicationExtension 10.15, tvOS 13.0, *)
public func changesetPublisher<T: Object>(_ object: T, keyPaths: [String]? = nil) -> RealmPublishers.ObjectChangeset<T> {
RealmPublishers.ObjectChangeset<T>(object, keyPaths: keyPaths)
}
/// Creates a publisher that emits an object changeset each time the object changes.
///
/// - precondition: The object must be a projection.
/// - parameter projection: A projection of Realm Object to observe.
/// - parameter keyPaths: The publisher emits changes on these property keyPaths. If `nil` the publisher emits changes for every property.
/// - returns: A publisher that emits an object changeset each time the projection changes.
@available(OSX 10.15, watchOS 6.0, iOS 13.0, iOSApplicationExtension 13.0, OSXApplicationExtension 10.15, tvOS 13.0, *)
public func changesetPublisher<T: ProjectionObservable>(_ projection: T, keyPaths: [String]? = nil) -> RealmPublishers.ProjectionChangeset<T> {
RealmPublishers.ProjectionChangeset<T>(projection, keyPaths: keyPaths)
}
/// Creates a publisher that emits a collection changeset each time the collection changes.
///
/// - precondition: The collection must be a managed collection which has not been invalidated.
/// - parameter object: A managed collection to observe.
/// - parameter keyPaths: The publisher emits changes on these property keyPaths. If `nil` the publisher emits changes for every property.
/// - returns: A publisher that emits a collection changeset each time the collection changes.
@available(OSX 10.15, watchOS 6.0, iOS 13.0, iOSApplicationExtension 13.0, OSXApplicationExtension 10.15, tvOS 13.0, *)
public func changesetPublisher<T: RealmCollection>(_ collection: T, keyPaths: [String]? = nil) -> RealmPublishers.CollectionChangeset<T> {
RealmPublishers.CollectionChangeset<T>(collection, keyPaths: keyPaths)
}
// MARK: - Realm
@available(OSX 10.15, watchOS 6.0, iOS 13.0, iOSApplicationExtension 13.0, OSXApplicationExtension 10.15, tvOS 13.0, *)
extension Realm {
/// A publisher that emits Void each time the object changes.
///
/// Despite the name, this actually emits *after* the collection has changed.
public var objectWillChange: RealmPublishers.RealmWillChange {
return RealmPublishers.RealmWillChange(self)
}
}
// MARK: - Object
@available(OSX 10.15, watchOS 6.0, iOS 13.0, iOSApplicationExtension 13.0, OSXApplicationExtension 10.15, tvOS 13.0, *)
extension Object: ObservableObject {
/// A publisher that emits Void each time the object changes.
///
/// Despite the name, this actually emits *after* the object has changed.
public var objectWillChange: RealmPublishers.WillChange<Object> {
return RealmPublishers.WillChange(self)
}
}
@available(OSX 10.15, watchOS 6.0, iOS 13.0, iOSApplicationExtension 13.0, OSXApplicationExtension 10.15, tvOS 13.0, *)
extension EmbeddedObject: ObservableObject {
/// A publisher that emits Void each time the object changes.
///
/// Despite the name, this actually emits *after* the embedded object has changed.
public var objectWillChange: RealmPublishers.WillChange<EmbeddedObject> {
return RealmPublishers.WillChange(self)
}
}
@available(OSX 10.15, watchOS 6.0, iOS 13.0, iOSApplicationExtension 13.0, OSXApplicationExtension 10.15, tvOS 13.0, *)
extension ObjectBase: RealmSubscribable {
/// :nodoc:
public func _observe<S>(_ keyPaths: [String]?, on queue: DispatchQueue?, _ subscriber: S) -> NotificationToken
where S.Input: ObjectBase, S: Subscriber, S.Failure == Error {
return _observe(keyPaths: keyPaths, on: queue) { (change: ObjectChange<S.Input>) in
switch change {
case .change(let object, _):
_ = subscriber.receive(object)
case .deleted:
subscriber.receive(completion: .finished)
case .error(let error):
subscriber.receive(completion: .failure(error))
}
}
}
/// :nodoc:
public func _observe<S>(_ keyPaths: [String]?, _ subscriber: S) -> NotificationToken where S: Subscriber, S.Failure == Never, S.Input == Void {
return _observe(keyPaths: keyPaths, { _ in _ = subscriber.receive()})
}
}
// MARK: - List
@available(OSX 10.15, watchOS 6.0, iOS 13.0, iOSApplicationExtension 13.0, OSXApplicationExtension 10.15, tvOS 13.0, *)
extension List: ObservableObject, RealmSubscribable {
/// A publisher that emits Void each time the collection changes.
///
/// Despite the name, this actually emits *after* the collection has changed.
public var objectWillChange: RealmPublishers.WillChange<List> {
RealmPublishers.WillChange(self)
}
}
// MARK: - MutableSet
@available(OSX 10.15, watchOS 6.0, iOS 13.0, iOSApplicationExtension 13.0, OSXApplicationExtension 10.15, tvOS 13.0, *)
extension MutableSet: ObservableObject, RealmSubscribable {
/// A publisher that emits Void each time the collection changes.
///
/// Despite the name, this actually emits *after* the collection has changed.
public var objectWillChange: RealmPublishers.WillChange<MutableSet> {
RealmPublishers.WillChange(self)
}
}
// MARK: - Map
@available(OSX 10.15, watchOS 6.0, iOS 13.0, iOSApplicationExtension 13.0, OSXApplicationExtension 10.15, tvOS 13.0, *)
extension Map: ObservableObject, RealmSubscribable {
/// A publisher that emits Void each time the collection changes.
///
/// Despite the name, this actually emits *after* the collection has changed.
public var objectWillChange: RealmPublishers.WillChange<Map> {
RealmPublishers.WillChange(self)
}
}
// MARK: - LinkingObjects
@available(OSX 10.15, watchOS 6.0, iOS 13.0, iOSApplicationExtension 13.0, OSXApplicationExtension 10.15, tvOS 13.0, *)
extension LinkingObjects: RealmSubscribable {
/// A publisher that emits Void each time the collection changes.
///
/// Despite the name, this actually emits *after* the collection has changed.
public var objectWillChange: RealmPublishers.WillChange<LinkingObjects> {
RealmPublishers.WillChange(self)
}
}
// MARK: - Results
@available(OSX 10.15, watchOS 6.0, iOS 13.0, iOSApplicationExtension 13.0, OSXApplicationExtension 10.15, tvOS 13.0, *)
extension Results: RealmSubscribable {
/// A publisher that emits Void each time the collection changes.
///
/// Despite the name, this actually emits *after* the collection has changed.
public var objectWillChange: RealmPublishers.WillChange<Results> {
RealmPublishers.WillChange(self)
}
}
// MARK: RealmCollection
@available(OSX 10.15, watchOS 6.0, iOS 13.0, iOSApplicationExtension 13.0, OSXApplicationExtension 10.15, tvOS 13.0, *)
extension RealmCollection {
/// :nodoc:
public func _observe<S>(_ keyPaths: [String]? = nil, on queue: DispatchQueue? = nil, _ subscriber: S)
-> NotificationToken where S: Subscriber, S.Input == Self, S.Failure == Error {
// FIXME: we could skip some pointless work in converting the changeset to the Swift type here
return observe(keyPaths: keyPaths, on: queue) { change in
switch change {
case .initial(let collection):
_ = subscriber.receive(collection)
case .update(let collection, deletions: _, insertions: _, modifications: _):
_ = subscriber.receive(collection)
case .error(let error):
subscriber.receive(completion: .failure(error))
}
}
}
/// :nodoc:
public func _observe<S: Subscriber>(_ keyPaths: [String]? = nil, _ subscriber: S) -> NotificationToken where S.Input == Void, S.Failure == Never {
return observe(keyPaths: keyPaths, on: nil) { _ in _ = subscriber.receive() }
}
}
@available(OSX 10.15, watchOS 6.0, iOS 13.0, iOSApplicationExtension 13.0, OSXApplicationExtension 10.15, tvOS 13.0, *)
extension AnyRealmCollection: RealmSubscribable {}
// MARK: RealmKeyedCollection
@available(OSX 10.15, watchOS 6.0, iOS 13.0, iOSApplicationExtension 13.0, OSXApplicationExtension 10.15, tvOS 13.0, *)
extension RealmKeyedCollection {
/// :nodoc:
public func _observe<S>(_ keyPaths: [String]?, on queue: DispatchQueue? = nil, _ subscriber: S)
-> NotificationToken where S: Subscriber, S.Input == Self, S.Failure == Error {
// FIXME: we could skip some pointless work in converting the changeset to the Swift type here
return observe(keyPaths: keyPaths, on: queue) { change in
switch change {
case .initial(let collection):
_ = subscriber.receive(collection)
case .update(let collection, deletions: _, insertions: _, modifications: _):
_ = subscriber.receive(collection)
case .error(let error):
subscriber.receive(completion: .failure(error))
}
}
}
/// :nodoc:
public func _observe<S: Subscriber>(_ subscriber: S) -> NotificationToken where S.Input == Void, S.Failure == Never {
return observe(keyPaths: nil, on: nil) { _ in _ = subscriber.receive() }
}
/// :nodoc:
public func _observe<S: Subscriber>(_ keyPaths: [String]? = nil, _ subscriber: S) -> NotificationToken where S.Input == Void, S.Failure == Never {
return observe(keyPaths: keyPaths, on: nil) { _ in _ = subscriber.receive() }
}
}
// MARK: Subscriptions
/// A subscription which wraps a Realm notification.
@available(OSX 10.15, watchOS 6.0, iOS 13.0, iOSApplicationExtension 13.0, OSXApplicationExtension 10.15, tvOS 13.0, *)
@frozen public struct ObservationSubscription: Subscription {
private var token: NotificationToken?
internal init(token: NotificationToken) {
self.token = token
}
internal init() {}
/// A unique identifier for identifying publisher streams.
public var combineIdentifier: CombineIdentifier {
return token != nil ? CombineIdentifier(token!) : CombineIdentifier(NSNumber(value: 0))
}
/// This function is not implemented.
///
/// Realm publishers do not support backpressure and so this function does nothing.
public func request(_ demand: Subscribers.Demand) {
}
/// Stop emitting values on this subscription.
public func cancel() {
token?.invalidate()
}
}
/// A subscription which wraps a Realm AsyncOpenTask.
@available(OSX 10.15, watchOS 6.0, iOS 13.0, iOSApplicationExtension 13.0, OSXApplicationExtension 10.15, tvOS 13.0, *)
@frozen public struct AsyncOpenSubscription: Subscription {
private let task: Realm.AsyncOpenTask
internal init(task: Realm.AsyncOpenTask,
callbackQueue: DispatchQueue,
onProgressNotificationCallback: ((SyncSession.Progress) -> Void)?) {
self.task = task
if let onProgressNotificationCallback = onProgressNotificationCallback {
self.task.addProgressNotification(queue: callbackQueue, block: onProgressNotificationCallback)
}
}
/// A unique identifier for identifying publisher streams.
public var combineIdentifier: CombineIdentifier {
return CombineIdentifier(task.rlmTask)
}
/// This function is not implemented.
///
/// Realm publishers do not support backpressure and so this function does nothing.
public func request(_ demand: Subscribers.Demand) {
}
/// Stop emitting values on this subscription.
public func cancel() {
task.cancel()
}
}
// MARK: Publishers
/// Combine publishers for Realm types.
///
/// You normally should not create any of these types directly, and should
/// instead use the extension methods which create them.
@available(OSX 10.15, watchOS 6.0, iOS 13.0, iOSApplicationExtension 13.0, OSXApplicationExtension 10.15, tvOS 13.0, *)
public enum RealmPublishers {
static private func realm<S: Scheduler>(_ config: RLMRealmConfiguration, _ scheduler: S) -> Realm? {
try? Realm(RLMRealm(configuration: config, queue: scheduler as? DispatchQueue))
}
static private func realm<S: Scheduler>(_ sourceRealm: Realm, _ scheduler: S) -> Realm? {
return realm(sourceRealm.rlmRealm.configuration, scheduler)
}
/// A publisher which emits an asynchronously opened Realm.
@frozen public struct AsyncOpenPublisher: Publisher {
/// This publisher can fail if there is an error opening the Realm.
public typealias Failure = Error
/// This publisher emits an opened Realm.
public typealias Output = Realm
private let configuration: Realm.Configuration
private let callbackQueue: DispatchQueue
private let onProgressNotificationCallback: ((SyncSession.Progress) -> Void)?
internal init(configuration: Realm.Configuration,
callbackQueue: DispatchQueue = .main,
onProgressNotificationCallback: ((SyncSession.Progress) -> Void)? = nil) {
self.configuration = configuration
self.callbackQueue = callbackQueue
self.onProgressNotificationCallback = onProgressNotificationCallback
}
/// Triggers an event when there is a notification on the async open progress.
///
/// This should be called directly after invoking the publisher.
///
/// - Parameter onProgressNotificationCallback: Callback which will be invoked when there is an update on progress.
/// - Returns: A publisher that emits an asynchronously opened Realm.
public func onProgressNotification(_ onProgressNotificationCallback: @escaping ((SyncSession.Progress) -> Void)) -> Self {
Self(configuration: configuration,
callbackQueue: callbackQueue,
onProgressNotificationCallback: onProgressNotificationCallback)
}
/// :nodoc:
public func receive<S>(subscriber: S) where S: Subscriber, S.Failure == Failure, Output == S.Input {
subscriber.receive(subscription: AsyncOpenSubscription(task: Realm.AsyncOpenTask(rlmTask: RLMRealm.asyncOpen(with: configuration.rlmConfiguration, callbackQueue: callbackQueue, callback: { rlmRealm, error in
if let realm = rlmRealm.flatMap(Realm.init) {
_ = subscriber.receive(realm)
subscriber.receive(completion: .finished)
} else {
subscriber.receive(completion: .failure(error ?? Realm.Error.callFailed))
}
})), callbackQueue: callbackQueue, onProgressNotificationCallback: onProgressNotificationCallback))
}
/// Specifies the scheduler on which to perform the async open task.
///
/// - parameter scheduler: The serial dispatch queue to receive values on.
/// - returns: A publisher which delivers values to the given scheduler.
public func receive<S: Scheduler>(on scheduler: S) -> Self {
guard let queue = scheduler as? DispatchQueue else {
fatalError("Cannot subscribe on scheduler \(scheduler): only serial dispatch queues are currently implemented.")
}
return Self(configuration: configuration,
callbackQueue: queue,
onProgressNotificationCallback: onProgressNotificationCallback)
}
}
/// A publisher which emits Void each time the Realm is refreshed.
///
/// Despite the name, this actually emits *after* the Realm is refreshed.
@frozen public struct RealmWillChange: Publisher {
/// This publisher cannot fail.
public typealias Failure = Never
/// This publisher emits Void.
public typealias Output = Void
private let realm: Realm
internal init(_ realm: Realm) {
self.realm = realm
}
/// Captures the `NotificationToken` produced by observing a Realm Collection.
///
/// This allows you to do notification skipping when performing a `Realm.write(withoutNotifying:)`. You should use this call if you
/// require to write to the Realm database and ignore this specific observation chain.
/// The `NotificationToken` will be saved on the specified `KeyPath`from the observation block set up in `receive(subscriber:)`.
///
/// - Parameters:
/// - object: The object which the `NotificationToken` is written to.
/// - keyPath: The KeyPath which the `NotificationToken` is written to.
/// - Returns: A `RealmWillChangeWithToken` Publisher.
public func saveToken<T>(on object: T, for keyPath: WritableKeyPath<T, NotificationToken?>) -> RealmWillChangeWithToken<T> {
return RealmWillChangeWithToken<T>(realm, object, keyPath)
}
/// :nodoc:
public func receive<S>(subscriber: S) where S: Subscriber, S.Failure == Never, Output == S.Input {
let token = self.realm.observe { _, _ in
_ = subscriber.receive()
}
subscriber.receive(subscription: ObservationSubscription(token: token))
}
}
/// :nodoc:
public class RealmWillChangeWithToken<T>: Publisher {
/// This publisher cannot fail.
public typealias Failure = Never
/// This publisher emits Void.
public typealias Output = Void
internal typealias TokenParent = T
internal typealias TokenKeyPath = WritableKeyPath<T, NotificationToken?>
private let realm: Realm
private var tokenParent: TokenParent
private var tokenKeyPath: TokenKeyPath
internal init(_ realm: Realm,
_ tokenParent: TokenParent,
_ tokenKeyPath: TokenKeyPath) {
self.realm = realm
self.tokenParent = tokenParent
self.tokenKeyPath = tokenKeyPath
}
/// :nodoc:
public func receive<S>(subscriber: S) where S: Subscriber, S.Failure == Never, Output == S.Input {
let token = self.realm.observe { _, _ in
_ = subscriber.receive()
}
tokenParent[keyPath: tokenKeyPath] = token
subscriber.receive(subscription: ObservationSubscription(token: token))
}
}
/// A publisher which emits Void each time the object is mutated.
///
/// Despite the name, this actually emits *after* the collection has changed.
@frozen public struct WillChange<Collection: RealmSubscribable>: Publisher where Collection: ThreadConfined {
/// This publisher cannot fail.
public typealias Failure = Never
/// This publisher emits Void.
public typealias Output = Void
private let collection: Collection
internal init(_ collection: Collection) {
self.collection = collection
}
/// Captures the `NotificationToken` produced by observing a Realm Collection.
///
/// This allows you to do notification skipping when performing a `Realm.write(withoutNotifying:)`. You should use this call if you
/// require to write to the Realm database and ignore this specific observation chain.
/// The `NotificationToken` will be saved on the specified `KeyPath`from the observation block set up in `receive(subscriber:)`.
///
/// - Parameters:
/// - object: The object which the `NotificationToken` is written to.
/// - keyPath: The KeyPath which the `NotificationToken` is written to.
/// - Returns: A `WillChangeWithToken` Publisher.
public func saveToken<T>(on object: T, at keyPath: WritableKeyPath<T, NotificationToken?>) -> WillChangeWithToken<Collection, T> {
return WillChangeWithToken<Collection, T>(collection, object, keyPath)
}
/// :nodoc:
public func receive<S>(subscriber: S) where S: Subscriber, S.Failure == Never, Output == S.Input {
let token = self.collection._observe(nil, subscriber)
subscriber.receive(subscription: ObservationSubscription(token: token))
}
}
/// A publisher which emits Void each time the object is mutated.
///
/// Despite the name, this actually emits *after* the collection has changed.
public class WillChangeWithToken<Collection: RealmSubscribable, T>: Publisher where Collection: ThreadConfined {
/// This publisher cannot fail.
public typealias Failure = Never
/// This publisher emits Void.
public typealias Output = Void
internal typealias TokenParent = T
internal typealias TokenKeyPath = WritableKeyPath<T, NotificationToken?>
private let object: Collection
private var tokenParent: TokenParent
private var tokenKeyPath: TokenKeyPath
internal init(_ object: Collection,
_ tokenParent: TokenParent,
_ tokenKeyPath: TokenKeyPath) {
self.object = object
self.tokenParent = tokenParent
self.tokenKeyPath = tokenKeyPath
}
/// :nodoc:
public func receive<S>(subscriber: S) where S: Subscriber, S.Failure == Never, Output == S.Input {
let token = self.object._observe(nil, subscriber)
tokenParent[keyPath: tokenKeyPath] = token
subscriber.receive(subscription: ObservationSubscription(token: token))
}
}
/// A publisher which emits an object or collection each time that object is mutated.
@frozen public struct Value<Subscribable: RealmSubscribable>: Publisher where Subscribable: ThreadConfined {
/// This publisher can only fail due to resource exhaustion when
/// creating the worker thread used for change notifications.
public typealias Failure = Error
/// This publisher emits the object or collection which it is publishing.
public typealias Output = Subscribable
private let subscribable: Subscribable
private let keyPaths: [String]?
private let queue: DispatchQueue?
internal init(_ subscribable: Subscribable, keyPaths: [String]? = nil, queue: DispatchQueue? = nil) {
precondition(subscribable.realm != nil, "Only managed objects can be published")
self.subscribable = subscribable
self.keyPaths = keyPaths
self.queue = queue
}
/// Captures the `NotificationToken` produced by observing a Realm Collection.
///
/// This allows you to do notification skipping when performing a `Realm.write(withoutNotifying:)`. You should use this call if you
/// require to write to the Realm database and ignore this specific observation chain.
/// The `NotificationToken` will be saved on the specified `KeyPath`from the observation block set up in `receive(subscriber:)`.
///
/// - Parameters:
/// - object: The object which the `NotificationToken` is written to.
/// - keyPath: The KeyPath which the `NotificationToken` is written to.
/// - Returns: A `ValueWithToken` Publisher.
public func saveToken<T>(on object: T, at keyPath: WritableKeyPath<T, NotificationToken?>) -> ValueWithToken<Subscribable, T> {
return ValueWithToken<Subscribable, T>(subscribable, queue, object, keyPath)