top of page
Writer's pictureSaurabh Singh

Use Streaming API in Lightning Component

You must have faced a situation where you need to refresh your lightning component in order to get the latest values. This problem arises when some other user or process modified the record. Using streaming API, you can subscribe to notification channel and you will get notification, when there is any update on the record.


Definition - Streaming API lets you push a stream of notifications from Salesforce to client apps based on criteria that you define.


First of all, you need to create push topics.

A PushTopic is an sObject that contains the criteria of events you want to listen to, such as data changes for a particular object. You define the criteria as a SOQL query in the PushTopic and specify the record operations to notify on (create, update, delete, and undelete). In addition to event criteria, a PushTopic represents the channel that client apps subscribe to.


Open your Anonymous window and execute below code.


PushTopic pushTopic = new PushTopic();
pushTopic.Name = 'AccountUpdates';
pushTopic.Query = 'SELECT Id, Name, Phone, Rating FROM Account where Rating=\'Hot\'';
pushTopic.ApiVersion = 46.0;
pushTopic.NotifyForOperationCreate = true;
pushTopic.NotifyForOperationUpdate = true;
pushTopic.NotifyForFields = 'Referenced';
insert pushTopic;

Above code would create a streaming channel named '/topic/AccountUpdates'.


After this PushTopic is created, you can subscribe to this PushTopic channel to track changes on accounts. This PushTopic specifies that the Id, Name, Phone and Rating fields are returned in each event notification. Notifications are send only for record that matches the query criteria.


Now let's create the lightning component that would subscribe to this streaming channel and receive notifications.


Component


Controller.js

Now create a Lightning Component tab and add this component to that tab.


output ->

Click on subscribe button to subscribe the /topic/AccountUpdates. You can unsubscribe to it by click on Unsubsribe button.

After click on Subscribe button, if subscribe is successful, you will see a alert message.

Now go to any account record and set its Rating to 'Hot'. You will see that modified account name is updated with recently changed Account record.


Let me know if you face any problem in doing above exercise in comment section.


2,826 views4 comments

Recent Posts

See All

4 Comments


Tejas
Tejas
Apr 12, 2021

the code works fine but when i refresh the page the push topic is unsubscribed...what can be the reason?

Like
Replying to

you need to subscribe on the page load

Like
bottom of page