lightning:empApi
Let's start off by creating a new Platform Event called "Demo_EmpApi_Event__e"...
...and add a new custom field called "Message__c".
Next, we need to add the reference to Emp API to our lightning component:
<lightning:empapi aura:id="empApi"></lightning:empapi>The bulk of the logic is handled by the init method in the controller class. The first thing that we need to do is to get a reference the Emp API component:
var empApi = cmp.find("empApi");
Once we have a reference to the Emp API component we can subscribe to the event:
var replayId=-1; //use -1 for new events
empApi.subscribe(channel, replayId, callback).then(function(value) { console.log("Subscribed to channel " + channel); sub = value; cmp.set("v.sub", sub); });
When we receive a message we need to handle is somehow. In this case I've created a callback function to popup an alert.
That's pretty much it! Now when we publish an event we get an alert.
var callback = function (message) { alert('Event Received!'); }.bind(this);The final piece of this is to publish the event. In order to do so, I've created an Apex class that instantiates the Demo_EmpApi_Event__e and then uses the EventBus Class to publish it.
Demo_EmpApi_Event__e event = new Demo_EmpApi_Event__e(Message__c=message); Database.SaveResult result = EventBus.publish(event);
I've posted the complete code examples below. Happy coding!
EmpApi_example.cmp
EmpApi_exampleController.js
EmpApi_exampleController.cls