Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Lightning Web Component Streaming API Demo
<template>
<!-- Push Topic -->
<c-lwc_streaming_api
channel="/topic/NewContactCreated"
api-version="45.0"
debug=true
onmessage={handleMessage}
onerror={handleError}
class="lwc_streaming_api-1">
</c-lwc_streaming_api>
<!-- Platform Event -->
<!--
<c-lwc_streaming_api
channel="/event/Test_Event__e"
api-version="45.0"
debug=true
onmessage={handleMessage}
onerror={handleError}
class="lwc_streaming_api-1">
</c-lwc_streaming_api>
-->
<lightning-button label="Destroy Connection" onclick={destroy}></lightning-button>
<lightning-button label="Restart Connection" onclick={restart}></lightning-button>
<lightning-button label="Check Connection" onclick={checkConnection}></lightning-button>
<div style="background: white;padding: 50px;">
<div style="margin:20px;">
Payload
<br/>
{payload}
</div>
<div style="margin:20px;">
Error:
<br/>
{error}
</div>
<div style="margin:20px;">
Is Connection On:
<br/>
{isConnectionOn}
</div>
</div>
</template>
import { LightningElement,track } from 'lwc';
export default class Lwc_streaming_demo extends LightningElement {
@track error = '';
@track payload = '';
@track isConnectionOn;
//Handles the error
handleError(event){
//Error is coming in the event.detail.error
this.error = JSON.stringify(event.detail.error);
}
//Handles the message/payload from streaming api
handleMessage(event){
//Message is coming in event.detail.payload
this.payload = this.payload + JSON.stringify(event.detail.payload);
}
//This methos is subscribing the channel
restart(){
this.template.querySelector('.lwc_streaming_api-1').subscribe();
}
//This methos is unsubscribing the channel
destroy(){
this.template.querySelector('.lwc_streaming_api-1').unsubscribe();
this.payload = '';
this.error = '';
}
//This methos is checking if the channel is subscribed or not
checkConnection(){
this.isConnectionOn = this.template.querySelector('.lwc_streaming_api-1').checkConnection();
}
}
<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata" fqn="lwc_streaming_demo">
<apiVersion>45.0</apiVersion>
<isExposed>true</isExposed>
<targets>
<target>lightning__HomePage</target>
</targets>
</LightningComponentBundle>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.