|
1 | 1 | import Foundation
|
2 | 2 | import StoreKit
|
3 | 3 |
|
| 4 | +public typealias TransactionUpdate = ((Transaction, String) async -> ()) |
| 5 | + |
4 | 6 | public class Mercato {
|
5 | 7 |
|
6 | 8 | private var purchaseController = PurchaseController()
|
7 | 9 | private var productService = ProductService()
|
8 |
| - |
9 |
| - public init() |
10 |
| - { |
11 |
| - |
12 |
| - } |
| 10 | + |
| 11 | + private var updateListenerTask: Task<(), Never>? = nil |
13 | 12 |
|
14 |
| - func listenForTransactions() async -> [(Transaction, String)] { |
15 |
| - var pending = [(Transaction, String)]() |
16 |
| - for await result in Transaction.updates |
| 13 | + public init() {} |
| 14 | + |
| 15 | + fileprivate func listenForTransactions(updateBlock: @escaping TransactionUpdate) { |
| 16 | + let task = Task.detached |
17 | 17 | {
|
18 |
| - do { |
19 |
| - let transaction = try checkVerified(result) |
20 |
| - pending.append((transaction, result.jwsRepresentation)) |
21 |
| - } catch { |
22 |
| - print("Transaction failed verification") |
| 18 | + for await result in Transaction.updates |
| 19 | + { |
| 20 | + do { |
| 21 | + let transaction = try checkVerified(result) |
| 22 | + await updateBlock(transaction, result.jwsRepresentation) |
| 23 | + } catch { |
| 24 | + print("Transaction failed verification") |
| 25 | + } |
23 | 26 | }
|
24 | 27 | }
|
25 |
| - return pending |
| 28 | + |
| 29 | + self.updateListenerTask = task |
26 | 30 | }
|
27 | 31 |
|
28 | 32 | //TODO: throw an error if productId are invalid
|
@@ -69,17 +73,21 @@ public class Mercato {
|
69 | 73 | throw error
|
70 | 74 | }
|
71 | 75 | }
|
| 76 | + |
| 77 | + deinit { |
| 78 | + updateListenerTask?.cancel() |
| 79 | + } |
72 | 80 | }
|
73 | 81 |
|
74 | 82 | extension Mercato
|
75 | 83 | {
|
76 | 84 | fileprivate static let shared: Mercato = .init()
|
77 | 85 |
|
78 |
| - public static func listenForTransactions() async -> [(Transaction, String)] |
79 |
| - { |
80 |
| - return await shared.listenForTransactions() |
81 |
| - } |
82 |
| - |
| 86 | + public static func listenForTransactions(updateBlock: @escaping TransactionUpdate) |
| 87 | + { |
| 88 | + shared.listenForTransactions(updateBlock: updateBlock) |
| 89 | + } |
| 90 | + |
83 | 91 | public static func retrieveProducts(productIds: Set<String>) async throws -> [Product]
|
84 | 92 | {
|
85 | 93 | try await shared.retrieveProducts(productIds: productIds)
|
|
0 commit comments