Created
December 1, 2017 12:54
-
-
Save Chudesnov/30a5e34170a74a3aa351327e23b17350 to your computer and use it in GitHub Desktop.
Observable
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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