Skip to content

Instantly share code, notes, and snippets.

@TheVishnuKumar
Last active January 2, 2020 21:38
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save TheVishnuKumar/c692e4a2c908e95b990966f36804ca14 to your computer and use it in GitHub Desktop.
Save TheVishnuKumar/c692e4a2c908e95b990966f36804ca14 to your computer and use it in GitHub Desktop.
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