Hub
Amplify has a local eventing system called Hub. It is a lightweight implementation of Publisher-Subscriber pattern, and is used to share data between modules and components in your app. Amplify uses Hub for different categories to communicate with one another when specific events occur, such as authentication events like a user sign-in or notification of a file download.
Working with the API
Listening for messages
You can use Amplify.Hub.listen(to: HubChannel) {...}
(listener) or Amplify.Hub.publisher(for: HubChannel).sink {...}
(Combine) to listen for messages that have been dispatched. Additionally, you can pass isIncluded: HubFilter
or eventName: HubPayloadEventName
to the listen
method to further filter Hub events. You can add multiple listeners to your application for different combinations of channels, filters, and events.
override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view.
// Assumes `unsubscribeToken` is declared as an instance variable in your view unsubscribeToken = Amplify.Hub.listen(to: .auth) { payload in switch payload.eventName { case HubPayload.EventName.Auth.signedIn: print("User signed in") // Update UI
case HubPayload.EventName.Auth.sessionExpired: print("Session expired") // Re-authenticate the user
case HubPayload.EventName.Auth.signedOut: print("User signed out") // Update UI
case HubPayload.EventName.Auth.userDeleted: print("User deleted") // Update UI
default: break } }}
override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view.
// Assumes `sink` is declared as an instance variable in your view controller sink = Amplify.Hub .publisher(for: .auth) .sink { payload in switch payload.eventName { case HubPayload.EventName.Auth.signedIn: print("User signed in") // Update UI
case HubPayload.EventName.Auth.sessionExpired: print("Session expired") // Re-authenticate the user
case HubPayload.EventName.Auth.signedOut: print("User signed out") // Update UI
case HubPayload.EventName.Auth.userDeleted: print("User deleted") // Update UI
default: break } }}
Stop Listening
Hub provides a way to stop listening for messages. This is useful if you no longer need to receive messages in your application flow.
// Assumes `unsubscribeToken` references the token// returned by Amplify.Hub.listen(...)Amplify.Hub.removeListener(unsubscribeToken)
// Assumes `sink` references the sink// returned by Amplify.Hub.publisher(...).sinksink.cancel()