Let’s explore one more powerful component of #Winter19.
lightning:empApi has below methods for use:
- subscribe – You need to call this method to subscribe to a channel to listen for events. It accepts channel name, replay id and callback method as arguments. This method will return subscription object.
- unsubscribe – Call this method to unsubscribe from a channel. You need to pass subscription object and an optional callback method as arguments.
- onError – This method will accept a callback method which will be called whenever an error is being thrown.
- setDebugFlag – Call this method to turn on/off browser console logging.
- isEmpEnabled – Returns true if the EmpJs Streaming API library can be used in this context; otherwise false. For example, if the component is hosted in Lightning Experience or Salesforce Mobile, this will return true. But if your component is hosted on communities/lightning out/visualforce/standalone app, then this will return false.
If you have gone through my previous post about service component to handle streaming event, we have created a similar component like lightning:empApi to handle the events. Let’s see the same “AccountSpy” example with lightning:empApi component.
Service Component – EmpApiDemo.cmp
Service Controller – EmpApiDemoController.js
Demo Component – AccountSpy.cmp
Demo Controller – AccountSpyController.js
Custom Component Event – EmpEvent.evt
- lightning:empApi component is capable of handling all type of events including recently introduced Change Data Capture events.
- lightning:empApi is only supported in Lightning Experience and Salesforce Mobile App for now. This component will not work in Lightning Communities, Visualforce, Lightning Out, and Standalone Lightning App.
- It’s always the best practice to unsubscribe from the event whenever a component is destroyed.
- Use setDebugFlag method to turn on browser console debugging.
Reference: Lightning Component Library
This component is very powerful especially in IoT world as everything depends on events now. Please do share your feedback or queries in comments.