import Combine
import StreamFeeds
class MyViewController: UIViewController {
@State private var cancellables = Set<AnyCancellable>()
let feedsClient: FeedsClient
override func viewDidLoad() {
super.viewDidLoad()
setupEventListening()
}
private func setupEventListening() {
feedsClient.eventPublisher
.sink { event in
self.handleEvent(event)
}
.store(in: &cancellables)
}
private func handleEvent(_ event: Event) {
switch event {
case let activityEvent as ActivityAddedEvent:
print("π New activity: \(activityEvent.activity.id)")
updateFeedUI()
case let pollEvent as PollClosedFeedEvent:
print("π Poll closed: \(pollEvent.poll.id)")
refreshPollData()
case let commentEvent as CommentAddedEvent:
print("π¬ New comment: \(commentEvent.comment.id)")
updateCommentsUI()
case let reactionEvent as ActivityReactionAddedEvent:
print("π Reaction added: \(reactionEvent.reaction.kind)")
updateReactionsUI()
case let followEvent as FollowCreatedEvent:
print("π₯ New follow: \(followEvent.follow.target)")
updateFollowCount()
case let bookmarkEvent as BookmarkAddedEvent:
print("π Bookmark added: \(bookmarkEvent.bookmark.id)")
updateBookmarksUI()
case let feedEvent as FeedCreatedEvent:
print("π Feed created: \(feedEvent.fid)")
refreshFeedList()
case let connectedEvent as ConnectedEvent:
print("π Connected to Stream with ID: \(connectedEvent.connectionId)")
case let errorEvent as ConnectionErrorEvent:
print("β Connection error: \(errorEvent.error)")
handleConnectionError()
default:
print("π‘ Received event: \(type(of: event))")
}
}
}Event Handling
This document explains how to listen to real-time events from Stream Feeds using the FeedsClient event publisher.
Overview
The FeedsClient provides two ways to listen to events:
- All Events: Listen to all events and handle them with type checking
- Specific Event Types: Listen to only specific event types for type-safe handling
Listening to All Events
Use the main eventPublisher to receive all events and handle them with type checking:
Listening to Specific Event Types
For type-safe event handling, use the generic eventPublisher(for:) method:
class ActivityHandler {
private var cancellables = Set<AnyCancellable>()
let feedsClient: FeedsClient
init(feedsClient: FeedsClient) {
self.feedsClient = feedsClient
setupActivityListeners()
}
private func setupActivityListeners() {
// Listen only to activity added events
feedsClient.eventPublisher(for: ActivityAddedEvent.self)
.sink { activityEvent in
print("New activity: \(activityEvent.activity.id)")
self.handleNewActivity(activityEvent)
}
.store(in: &cancellables)
// Listen only to activity updated events
feedsClient.eventPublisher(for: ActivityUpdatedEvent.self)
.sink { activityEvent in
print("Activity updated: \(activityEvent.activity.id)")
self.handleActivityUpdate(activityEvent)
}
.store(in: &cancellables)
// Listen only to activity deleted events
feedsClient.eventPublisher(for: ActivityDeletedEvent.self)
.sink { activityEvent in
print("Activity deleted: \(activityEvent.activity.id)")
self.handleActivityDeletion(activityEvent)
}
.store(in: &cancellables)
}
private func handleNewActivity(_ event: ActivityAddedEvent) {
// Handle new activity
}
private func handleActivityUpdate(_ event: ActivityUpdatedEvent) {
// Handle activity update
}
private func handleActivityDeletion(_ event: ActivityDeletedEvent) {
// Handle activity deletion
}
}Multiple Event Type Listeners
You can set up multiple listeners for different event types:
class FeedManager {
private var cancellables = Set<AnyCancellable>()
let feedsClient: FeedsClient
init(feedsClient: FeedsClient) {
self.feedsClient = feedsClient
setupEventListeners()
}
private func setupEventListeners() {
// Activity events
feedsClient.eventPublisher(for: ActivityAddedEvent.self)
.sink { [weak self] event in
self?.handleActivityAdded(event)
}
.store(in: &cancellables)
// Comment events
feedsClient.eventPublisher(for: CommentAddedEvent.self)
.sink { [weak self] event in
self?.handleCommentAdded(event)
}
.store(in: &cancellables)
// Poll events
feedsClient.eventPublisher(for: PollVoteCastedFeedEvent.self)
.sink { [weak self] event in
self?.handlePollVote(event)
}
.store(in: &cancellables)
// Connection events
feedsClient.eventPublisher(for: ConnectedEvent.self)
.sink { [weak self] event in
self?.handleConnection(event)
}
.store(in: &cancellables)
}
}SwiftUI Integration
Here's how to listen to events in SwiftUI:
struct FeedView: View {
@StateObject private var viewModel: FeedViewModel
@State private var cancellables = Set<AnyCancellable>()
var body: some View {
List(viewModel.activities) { activity in
ActivityRow(activity: activity)
}
.onAppear {
setupEventListening()
}
.onDisappear {
cancellables.removeAll()
}
}
private func setupEventListening() {
viewModel.feedsClient.eventPublisher(for: ActivityAddedEvent.self)
.receive(on: DispatchQueue.main)
.sink { event in
viewModel.addActivity(event.activity)
}
.store(in: &cancellables)
viewModel.feedsClient.eventPublisher(for: ActivityUpdatedEvent.self)
.receive(on: DispatchQueue.main)
.sink { event in
viewModel.updateActivity(event.activity)
}
.store(in: &cancellables)
}
}Available Event Types
Below is a comprehensive table of all available event types and their descriptions:
| Event Name | Description |
|---|---|
| Activity Events | |
ActivityAddedEvent | Fired when a new activity is added to a feed |
ActivityUpdatedEvent | Fired when an activity is modified |
ActivityDeletedEvent | Fired when an activity is removed |
ActivityRestoredEvent | Fired when an activity is restored |
ActivityRemovedFromFeedEvent | Fired when an activity is removed from a specific feed |
ActivityMarkEvent | Fired when activities are marked as read/seen |
ActivityPinnedEvent | Fired when an activity is pinned to the top |
ActivityUnpinnedEvent | Fired when an activity is unpinned |
| Comment Events | |
CommentAddedEvent | Fired when a new comment is added to an activity |
CommentUpdatedEvent | Fired when a comment is modified |
CommentDeletedEvent | Fired when a comment is removed |
| Reaction Events | |
ActivityReactionAddedEvent | Fired when a reaction is added to an activity |
ActivityReactionDeletedEvent | Fired when a reaction is removed from an activity |
CommentReactionAddedEvent | Fired when a reaction is added to a comment |
CommentReactionDeletedEvent | Fired when a reaction is removed from a comment |
| Poll Events | |
PollClosedFeedEvent | Fired when a poll is closed |
PollDeletedFeedEvent | Fired when a poll is deleted |
PollUpdatedFeedEvent | Fired when a poll is modified |
PollVoteCastedFeedEvent | Fired when a vote is cast |
PollVoteChangedFeedEvent | Fired when a vote is changed |
PollVoteRemovedFeedEvent | Fired when a vote is removed |
| Feed Events | |
FeedCreatedEvent | Fired when a new feed is created |
FeedUpdatedEvent | Fired when a feed is modified |
FeedDeletedEvent | Fired when a feed is deleted |
FeedGroupChangedEvent | Fired when a feed group is modified |
FeedGroupDeletedEvent | Fired when a feed group is deleted |
| Member Events | |
FeedMemberAddedEvent | Fired when a member is added to a feed |
FeedMemberRemovedEvent | Fired when a member is removed from a feed |
FeedMemberUpdatedEvent | Fired when a member's role/permissions change |
| Follow Events | |
FollowCreatedEvent | Fired when a follow relationship is created |
FollowDeletedEvent | Fired when a follow relationship is removed |
FollowUpdatedEvent | Fired when follow settings are modified |
| Bookmark Events | |
BookmarkAddedEvent | Fired when an activity is bookmarked |
BookmarkDeletedEvent | Fired when a bookmark is removed |
BookmarkUpdatedEvent | Fired when bookmark metadata is modified |
| Connection Events | |
ConnectedEvent | Fired when successfully connected to WebSocket |
ConnectionErrorEvent | Fired when connection fails or errors occur |
HealthCheckEvent | Fired when health check is received |
You can configure your Stream app to receive webhook events as well as AWS SNS and AWS SQS. Webhooks are usually the simplest way to receive events from your app and to perform additional action based on what happens to your application.
The configuration can be done using the API or from the Dashboard. By default, all events are sent to your webhook/sqs/sns endpoint, you can also configure the events you want to receive in the dashboard.
await serverAuthClient.updateAppSettings({
event_hooks: [
{
hook_type: "webhook",
enabled: true,
// Pass an empty array to subscribe to all events
event_types: [],
webhook_url: "<webhook url>",
},
{
hook_type: "webhook",
enabled: true,
// Subscribe only to specific events
event_types: ["feeds.activity.added" /* ... */],
webhook_url: "<webhook url>",
},
],
});Some important points to consider:
- The selection of events you want to receive applies to all the endpoints you have configured.
- You can configure multiple endpoints for the same app (eg. AWS SNS and HTTP Webhook).
- If your app is configured to receive all events, you can still filter the events you want to receive in your webhook handler.
- If your app is configured to receive all events, newly introduced event types will be sent to your webhook handler by default.
- If you pick specific events, newly introduced event types will not be sent to your webhook handler by default (you can still manually add them later on).
How to implement a webhook handler
Your webhook handler needs to follow these rules:
- accept HTTP POST requests with JSON payload
- be reachable from the public internet. Tunneling services like Ngrok are supported
- respond with response codes from 200 to 299 as fast as possible
Your webhook handler can use the type field to handle events based correctly based on their type and payload.
All webhook requests contain these headers:
| Name | Description |
|---|---|
| X-WEBHOOK-ID | Unique ID of the webhook call. This value is consistent between retries and could be used to deduplicate retry calls |
| X-WEBHOOK-ATTEMPT | Number of webhook request attempt starting from 1 |
| X-API-KEY | Your applicationβs API key. Should be used to validate request signature |
| X-SIGNATURE | HMAC signature of the request body. See Signature section |
Best Practices
We highly recommend following common security guidelines to make your webhook integration safe and fast:
- Use HTTPS with a certificate from a trusted authority
- Verify the "X-Signature" header to ensure the request is coming from Stream
- Support HTTP Keep-Alive
- Use a highly available infrastructure such as AWS Elastic Load Balancer, Google Cloud Load Balancer, or similar
- Offload the processing of the message if possible (read, store, and forget)
- When decoding JSON into objects, ensure that your webhook can handle new fields being added to the JSON payload as well as new event types (eg. log unknown fields and event types instead of failing)
Error Handling
In case of the request failure Stream Chat attempts to retry a request. The amount of maximum attempts depends on the kind of the error it receives:
- Response code is 408, 429 or >=500: 3 attempts
- Network error: 2 attempts
- Request timeout: 3 attempts
The timeout of one request is 6 seconds, and the request with all retries cannot exceed the duration of 15 seconds.
Available Event Types
Below is a comprehensive table of all available event types and their descriptions. WebhookEvent model definition can be found in Open API specification.
| Event Name | Description |
|---|---|
| Activity Events | |
feeds.activity.added | Fired when a new activity is added to a feed |
feeds.activity.updated | Fired when an activity is modified |
feeds.activity.deleted | Fired when an activity is removed |
feeds.activity.restored | Fired when an activity is restored |
feeds.activity.removed_from_feed | Fired when an activity is removed from a specific feed |
feeds.activity.pinned | Fired when an activity is pinned to the top |
feeds.activity.unpinned | Fired when an activity is unpinned |
feeds.activity.feedback | Fired when activity feedback is provided |
feeds.activity.marked | Fired when an activity is marked |
| Notification Events | |
feeds.notification_feed.updated | Fired when the notification status, or notification groups (aggregated activities) are updated |
| Comment Events | |
feeds.comment.added | Fired when a new comment is added to an activity |
feeds.comment.updated | Fired when a comment is modified |
feeds.comment.deleted | Fired when a comment is removed |
| Reaction Events | |
feeds.activity.reaction.added | Fired when a reaction is added to an activity |
feeds.activity.reaction.deleted | Fired when a reaction is removed from an activity |
feeds.activity.reaction.updated | Fired when a reaction on an activity is updated |
feeds.comment.reaction.added | Fired when a reaction is added to a comment |
feeds.comment.reaction.deleted | Fired when a reaction is removed from a comment |
feeds.comment.reaction.updated | Fired when a reaction on a comment is updated |
| Poll Events | |
feeds.poll.closed | Fired when a poll is closed |
feeds.poll.deleted | Fired when a poll is deleted |
feeds.poll.updated | Fired when a poll is modified |
feeds.poll.vote_casted | Fired when a vote is cast |
feeds.poll.vote_changed | Fired when a vote is changed |
feeds.poll.vote_removed | Fired when a vote is removed |
| Feed Events | |
feeds.feed.created | Fired when a new feed is created |
feeds.feed.updated | Fired when a feed is modified |
feeds.feed.deleted | Fired when a feed is deleted |
| Feed Group Events | |
feeds.feed_group.changed | Fired when a feed group is changed |
feeds.feed_group.deleted | Fired when a feed group is deleted |
| Member Events | |
feeds.feed_member.added | Fired when a member is added to a feed |
feeds.feed_member.removed | Fired when a member is removed from a feed |
feeds.feed_member.updated | Fired when a member's role/permissions change |
| Follow Events | |
feeds.follow.created | Fired when a follow relationship is created |
feeds.follow.deleted | Fired when a follow relationship is removed |
feeds.follow.updated | Fired when follow settings are modified |
| Bookmark Events | |
feeds.bookmark.added | Fired when an activity is bookmarked |
feeds.bookmark.deleted | Fired when a bookmark is removed |
feeds.bookmark.updated | Fired when bookmark metadata is modified |
feeds.bookmark_folder.deleted | Fired when bookmark folder is deleted |
feeds.bookmark_folder.updated | Fired when bookmark folder is updated |
| Stories Events | |
feeds.stories_feed.updated | Fired when a stories feed is updated |
| Moderation Events | |
moderation.custom_action | Fired when a custom moderation action is performed |
moderation.flagged | Fired when content is flagged for moderation |
moderation.mark_reviewed | Fired when content is marked as reviewed |
| User Events | |
user.banned | Fired when a user is banned |
user.deactivated | Fired when a user is deactivated |
user.muted | Fired when a user is muted |
user.reactivated | Fired when a user is reactivated |
user.updated | Fired when a user is updated |