Skip to content

Instantly share code, notes, and snippets.

@rjstires
Last active March 8, 2018 02:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save rjstires/071aee8ce253a278681f4ef2a9e2d7fd to your computer and use it in GitHub Desktop.
Save rjstires/071aee8ce253a278681f4ef2a9e2d7fd to your computer and use it in GitHub Desktop.
new_events_observable.js
import * as Rx from 'rxjs/Rx';
import { API_ROOT } from 'src/constants';
import Axios, { AxiosResponse } from 'axios';
import * as moment from 'moment';
function createDatestamp() {
return moment().utc().format('YYYY-MM-DDTHH:mm:ss');
}
let datestamp = createDatestamp();
type EventResponse = AxiosResponse<Linode.ManyResourceState<Linode.Event>>;
/** Get events. */
const initial$ = Rx.Observable
.defer(() =>
Rx.Observable
.fromPromise(
Axios.get(`${API_ROOT}/account/events`)
.then(
(response: EventResponse) => response.data.data.slice(0, 5),
),
));
/** Get events. */
const polling$ = Rx.Observable
.interval(5000)
.flatMap(() =>
Rx.Observable
.fromPromise(
Axios.get(
`${API_ROOT}/account/events`,
{ headers: { 'X-Filter': JSON.stringify({ created: { '+gt': datestamp } }) } })
.then((response: EventResponse) => response.data.data),
),
);
const stream$: Rx.Observable<Linode.Event[]> = Rx.Observable
.merge(initial$, polling$)
.scan(
(acc, value) => {
if (value[0]) {
datestamp = value[0].created;
}
return [...value, ...acc].splice(0, 5);
},
[],
);
const exp$ = stream$
.publish();
/** Example of how we'd get the events for the dropdown. */
exp$.subscribe(
(events: Linode.Event[]) => console.log('Events: ', events.map(e => e.id).join(', ')),
);
/** Example of how we would get the badge count. */
exp$
.map(events => events.reduce((acc, current) => current.seen ? acc : acc + 1, 0))
.subscribe((e) => { console.log('Unseed Events:', e); });
exp$.connect();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment