I recently discovered that Salesforce Lightning Communities do not offer support for Streaming API or Events APIs. Consequently, you cannot utilize EMAPI on AURA/LWC for communities. This prompted me to explore a workaround in an Aura component.
<aura:component implements="force:appHostable,flexipage:availableForAllPageTypes,flexipage:availableForRecordHome,force:hasRecordId,forceCommunity:availableForAllPageTypes,force:lightningQuickAction" controller="RefreshContactCounter" access="global" >
<aura:attribute name="recordId" type="Id"></aura:attribute>
<aura:attribute name="pollId" type="String"></aura:attribute>
<lightning:button variant="brand" label="Subscribe" title="Subscribe" onclick="{!c.init}" />
<lightning:button variant="brand-outline" label="Stop" title="Stop" onclick="{!c.cancelSubscribe}" />
</aura:component>
({
checkSubscribeCall: function(component, event, helper){
//execute callApexMethod() again after 5 sec each
var pollId = window.setInterval(
$A.getCallback(function() {
// Calling Apex Method
helper.callApexMethod(component,helper,pollId);
}), 5000
);
},
handleResponse : function (response, component){
var retVal = response.getReturnValue() ;
// Your Logic
},
callApexMethod : function (component,helper,pollId){
// Setting current pollId to stop the loop
component.set('v.pollId', pollId);
// Setting Apex Method
var action = component.get("c.getContactCount");
// Setting Apex Param
action.setParams({ Id : component.get("v.recordId") });
// Call Back Action
action.setCallback(this, function(response) {
this.handleResponse(response, component);
});
$A.enqueueAction(action);
}
})
({
init : function(component, event, helper) {
// Calling Helper
helper.checkSubscribeCall(component, event,helper);
},
cancelSubscribe : function (component, event, helper){
window.clearInterval(component.get('v.pollId'));
}
})
public class RefreshContactCounter {
@AuraEnabled
public static Integer getContactCount(){
AggregateResult[] groupedResults = [SELECT count(Id) totalCount FROM Contact];
Object totalCount = groupedResults[0].get('totalCount');
return (Integer) totalCount ;
}
}
