Skip to content

Instantly share code, notes, and snippets.

@Chudesnov
Created December 1, 2017 12:54
Show Gist options
  • Save Chudesnov/30a5e34170a74a3aa351327e23b17350 to your computer and use it in GitHub Desktop.
Save Chudesnov/30a5e34170a74a3aa351327e23b17350 to your computer and use it in GitHub Desktop.
Observable
function myUpload (url, file) {
return new Observable(subscriber => {
const request = new XMLHttpRequest();
request.onload = function(data) {
subscriber.next(data);
subscriber.complete();
}
request.onerror = function(error) {
subscriber.error(error);
}
request.send();
return function() {
request.abort();
}
});
}
const uploadObservable = myUpload('', file);
const uploadSubscription = upload.subscribe({
next: () => {}
})
const uploadSubscription2 = upload.subscribe({
next: () => {}
})
button.addEventListener('click', uploadSubscription.unsubscribe);
function getEventStream(eventType) {
const observers = [];
const handler = event => {
console.log('log');
observers.forEach(observer => observer.next(event));
}
return new Observable(observer => {
observers.push(observer);
if (observers.length === 1) {
document.addEventListener(eventType, handler);
}
return () => {
observers.remove(observer);
if (observers.length === 0) {
document.removeEventListener(eventType, handler);
}
}
});
}
const clicks = getEventStream('click');
simulateClick(); //
const sub = clicks.subscribe({
next: () => { console.log() }
});
simulateClick(); // log
const subscription = [0,1,2,3,4].map(
() => clicks.subscribe({
next: () => { console.log() }
})
);
simulateClick(); // log
subscription[0].unsubscribe();
simulateClick(); // log
subscription[1].unsubscribe();
simulateClick(); // log
subscription[2].unsubscribe();
simulateClick(); // log
subscription[3].unsubscribe();
simulateClick(); // log
subscription[4].unsubscribe();
simulateClick(); //
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment