<div>
	<h1>A small example of using RxJs.</h1>
	<blockquote>Here we create an <em>observable</em> with the RxJs  <code>of</code> function. We then use <code>pipe</code> to take the values (here just "true") into a flow. We use the <code>delay</code> operator to wait for a number of ms. The <code>tap</code> operator lets us "tap into" a stream and "do something". We log some information, and repeat that pattern 3 times, after which the stream ends.<br><br>
		To start the pattern we use <code>subscribe</code> and after the flow has ended we <code>unsubscribe</code> to the observable stream.
	</blockquote>
<button id="start">Start the observablePattern</button>
	<div id="log"></div>
</div>

<div class="box"></div>
:root {
	--size: 100px;
}
html,body {
	margin:0;
	padding: 0;
	width: 100%;
	height: 100%;
}
body {
	display: flex;
	align-items: center;
	justify-content: center;
	text-align: center;
	font-family: sans-serif;
}
#log {
	height: 5em;
	margin: 10px;
	color: #0055ff;
}
code {
	padding: 4px;
	background: #ddd;
	margin: 0 2px;
}

.box {
	position: fixed;
	bottom: var(--size);
	right: var(--size);
	width: var(--size);
	height: var(--size);
	background: orange;
	opacity: .5;
	transition: all ease-in-out .7s ;
}
const {of, operators } = rxjs;
const { delay, tap } = operators;
// A RxJs pattern is defined but not executed
// before "someone" subscribes on it.
const observablePattern = of(true)
	.pipe(
		delay(100),
		tap(() => {
			log('After 100 ms');
			setSize(50);
		}),
		delay(1000),
		tap(() => {
			log('After another 1000 ms')
			setSize(150);
		}),
		delay(500),
		tap(() => {
			log('After another 500 ms');
			setSize(100);
		})
	);

let subscription;
const startButton = document.getElementById('start');
const logArea = document.getElementById('log');
startButton
	.addEventListener('click', () => {
	logArea.innerHTML = ''
	log('Stream started...')
		subscription = observablePattern.subscribe(() => {
			// Remember to unsubscribe when done
			subscription.unsubscribe();
			log('Stream ended..')
		})
  });

function log(s) {
	logArea.innerHTML += `<pre>${new Date().toLocaleTimeString()} ${s}</pre>`
}

function setSize(size) {
	document.documentElement.style.setProperty('--size', `${size}px`)
}

External CSS

This Pen doesn't use any external CSS resources.

External JavaScript

  1. https://cdnjs.cloudflare.com/ajax/libs/rxjs/6.6.3/rxjs.umd.min.js