import all0 from "/src/fragments/guides/api-graphql/common/subscriptions-by-id.mdx";
```swift
extension GraphQLRequest {
static func onCreateComment(byPostId id: String) -> GraphQLRequest {
let operationName = "onCommentByPostId"
let document = """
subscription onCreateCommentByPostId($id:ID!) {
\(operationName)(postCommentsId: $id) {
content
id
postCommentsId
}
}
"""
return GraphQLRequest(document: document,
variables: ["id": id],
responseType: Comment.self,
decodePath: operationName)
}
}
```
Because the lifetime of the subscription will last longer than the lifetime of a single function, you can create an instance variable at the top of your class:
```swift
var subscription: AmplifyAsyncThrowingSequence>!
```
```swift
var cancellable: AnyCancellable?
```
To listen to creation updates with the specific post using the post id, you can use the following code sample:
```swift
func createSubscription() {
subscription = Amplify.API.subscribe(
request: .onCreateComment(byPostId: "12345")
)
Task {
do {
for try await subscriptionEvent in subscription {
switch subscriptionEvent {
case .connection(let subscriptionConnectionState):
print("Subscription connect state is \(subscriptionConnectionState)")
case .data(let result):
switch result {
case .success(let createdComment):
print("Successfully got comment from subscription: \(createdComment)")
case .failure(let error):
print("Got failed result with \(error.errorDescription)")
}
}
}
} catch {
print("Subscription has terminated with \(error)")
}
}
}
```
```swift
func createSubscription() {
let sequence = Amplify.API.subscribe(
request: .onCreateComment(byPostId: "12345")
)
cancellable = Amplify.Publisher.create(sequence)
.sink(
receiveCompletion: {
if case let .failure(apiError) = $0 {
print("Subscription has terminated with \(apiError)")
} else {
print("Subscription has been closed successfully")
}
},
receiveValue: { result in
switch result {
case .connection(let subscriptionConnectionState):
print("Subscription connect state is \(subscriptionConnectionState)")
case .data(let result):
switch result {
case .success(let createdComment):
print("Successfully got comment from subscription: \(createdComment)")
case .failure(let error):
print("Got failed result with \(error.errorDescription)")
}
}
}
)
}
```