@@ -448,6 +448,65 @@ class GraphQLModelBasedTests: XCTestCase {
448
448
await fulfillment ( of: [ progressInvoked] , timeout: TestCommonConstants . networkTimeout)
449
449
}
450
450
451
+
452
+ /// Given: Several subscriptions with Amplify API plugin
453
+ /// When: Cancel subscriptions
454
+ /// Then: AppSync real time client automatically unsubscribe and remove the subscription
455
+ func testCancelledSubscription_automaticallyUnsubscribeAndRemoved( ) async throws {
456
+ let numberOfSubscription = 5
457
+ let allSubscribedExpectation = expectation ( description: " All subscriptions are subscribed " )
458
+ allSubscribedExpectation. expectedFulfillmentCount = numberOfSubscription
459
+
460
+ let subscriptions = ( 0 ..< 5 ) . map { _ in
461
+ Amplify . API. subscribe ( request: . subscription( of: Comment . self, type: . onCreate) )
462
+ }
463
+ subscriptions. forEach { subscription in
464
+ Task {
465
+ do {
466
+ for try await subscriptionEvent in subscription {
467
+ switch subscriptionEvent {
468
+ case . connection( let state) :
469
+ switch state {
470
+ case . connecting:
471
+ break
472
+ case . connected:
473
+ allSubscribedExpectation. fulfill ( )
474
+ case . disconnected:
475
+ break
476
+ }
477
+ case . data( let result) :
478
+ switch result {
479
+ case . success: break
480
+ case . failure( let error) :
481
+ XCTFail ( " \( error) " )
482
+ }
483
+ }
484
+ }
485
+ } catch {
486
+ XCTFail ( " Unexpected subscription failure " )
487
+ }
488
+ }
489
+ }
490
+
491
+ await fulfillment ( of: [ allSubscribedExpectation] , timeout: 3 )
492
+ if let appSyncRealTimeClientFactory =
493
+ getUnderlyingAPIPlugin ( ) ? . appSyncRealTimeClientFactory as? AppSyncRealTimeClientFactory ,
494
+ let appSyncRealTimeClient =
495
+ await appSyncRealTimeClientFactory. apiToClientCache. values. first as? AppSyncRealTimeClient
496
+ {
497
+ var appSyncSubscriptions = await appSyncRealTimeClient. numberOfSubscriptions
498
+ XCTAssertEqual ( appSyncSubscriptions, numberOfSubscription)
499
+
500
+ subscriptions. forEach { $0. cancel ( ) }
501
+ try await Task . sleep ( seconds: 2 )
502
+ appSyncSubscriptions = await appSyncRealTimeClient. numberOfSubscriptions
503
+ XCTAssertEqual ( appSyncSubscriptions, 0 )
504
+
505
+ } else {
506
+ XCTFail ( " There should be at least one AppSyncRealTimeClient instance " )
507
+ }
508
+ }
509
+
451
510
// MARK: Helpers
452
511
453
512
func createPost( id: String , title: String ) async throws -> Post ? {
@@ -499,4 +558,8 @@ class GraphQLModelBasedTests: XCTestCase {
499
558
throw error
500
559
}
501
560
}
561
+
562
+ func getUnderlyingAPIPlugin( ) -> AWSAPIPlugin ? {
563
+ return Amplify . API. plugins [ " awsAPIPlugin " ] as? AWSAPIPlugin
564
+ }
502
565
}
0 commit comments