@@ -32,8 +32,12 @@ public extension HKStatisticsQuery {
3232
3333public extension HKAnchoredObjectQuery {
3434 static func promise( type: HKSampleType , predicate: NSPredicate ? = nil , anchor: HKQueryAnchor ? = nil , limit: Int = HKObjectQueryNoLimit, healthStore: HKHealthStore = . init( ) ) -> Promise < ( [ HKSample ] , [ HKDeletedObject ] , HKQueryAnchor ) > {
35- return Promise { seal in
36- let query = HKAnchoredObjectQuery ( type: type, predicate: predicate, anchor: anchor, limit: limit) {
35+ var query : HKAnchoredObjectQuery !
36+ var reject : ( ( Error ) -> Void ) !
37+
38+ let promise = Promise< ( [ HKSample] , [ HKDeletedObject] , HKQueryAnchor) > { seal in
39+ reject = seal. reject
40+ query = HKAnchoredObjectQuery ( type: type, predicate: predicate, anchor: anchor, limit: limit) {
3741 if let a = $1, let b = $2, let c = $3 {
3842 seal. fulfill ( ( a, b, c) )
3943 } else if let e = $4 {
@@ -44,13 +48,16 @@ public extension HKAnchoredObjectQuery {
4448 }
4549 healthStore. execute ( query)
4650 }
51+
52+ promise. setCancellableTask ( LongRunningQuery ( healthStore: healthStore, query: query) , reject: reject)
53+ return promise
4754 }
4855
4956}
5057
5158public extension HKStatisticsCollectionQuery {
5259 func promise( healthStore: HKHealthStore = . init( ) ) -> Promise < HKStatisticsCollection > {
53- return Promise { seal in
60+ return Promise ( cancellableTask : LongRunningQuery ( healthStore : healthStore , query : self ) ) { seal in
5461 initialResultsHandler = {
5562 seal. resolve ( $1, $2)
5663 }
@@ -69,3 +76,34 @@ public extension HKSampleQuery {
6976 }
7077 }
7178}
79+
80+ class LongRunningQuery : CancellableTask {
81+ let healthStore : HKHealthStore
82+ let query : HKQuery
83+
84+ init ( healthStore: HKHealthStore , query: HKQuery ) {
85+ self . healthStore = healthStore
86+ self . query = query
87+ }
88+
89+ func cancel( ) {
90+ healthStore. stop ( query)
91+ isCancelled = true
92+ }
93+
94+ var isCancelled = false
95+ }
96+
97+ //////////////////////////////////////////////////////////// Cancellable wrappers
98+
99+ public extension HKAnchoredObjectQuery {
100+ static func cancellablePromise( type: HKSampleType , predicate: NSPredicate ? = nil , anchor: HKQueryAnchor ? = nil , limit: Int = HKObjectQueryNoLimit, healthStore: HKHealthStore = . init( ) ) -> CancellablePromise < ( [ HKSample ] , [ HKDeletedObject ] , HKQueryAnchor ) > {
101+ return cancellable ( promise ( type: type, predicate: predicate, anchor: anchor, limit: limit, healthStore: healthStore) )
102+ }
103+ }
104+
105+ public extension HKStatisticsCollectionQuery {
106+ func cancellablePromise( healthStore: HKHealthStore = . init( ) ) -> CancellablePromise < HKStatisticsCollection > {
107+ return cancellable ( promise ( healthStore: healthStore) )
108+ }
109+ }
0 commit comments