Skip to content

Commit c75bddc

Browse files
Merge pull request #4 from dapperlabs/sl/update_listener
update listener again
2 parents 22711f4 + 643e48c commit c75bddc

File tree

1 file changed

+27
-19
lines changed

1 file changed

+27
-19
lines changed

Sources/Mercato/Mercato.swift

+27-19
Original file line numberDiff line numberDiff line change
@@ -1,28 +1,32 @@
11
import Foundation
22
import StoreKit
33

4+
public typealias TransactionUpdate = ((Transaction, String) async -> ())
5+
46
public class Mercato {
57

68
private var purchaseController = PurchaseController()
79
private var productService = ProductService()
8-
9-
public init()
10-
{
11-
12-
}
10+
11+
private var updateListenerTask: Task<(), Never>? = nil
1312

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
1717
{
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+
}
2326
}
2427
}
25-
return pending
28+
29+
self.updateListenerTask = task
2630
}
2731

2832
//TODO: throw an error if productId are invalid
@@ -69,17 +73,21 @@ public class Mercato {
6973
throw error
7074
}
7175
}
76+
77+
deinit {
78+
updateListenerTask?.cancel()
79+
}
7280
}
7381

7482
extension Mercato
7583
{
7684
fileprivate static let shared: Mercato = .init()
7785

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+
8391
public static func retrieveProducts(productIds: Set<String>) async throws -> [Product]
8492
{
8593
try await shared.retrieveProducts(productIds: productIds)

0 commit comments

Comments
 (0)