Advertisement
Guest User

Untitled

a guest
Apr 29th, 2016
50
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.75 KB | None | 0 0
  1. console.clear()
  2.  
  3. class RealDealObserver {
  4. constructor(destination) {
  5. this.destination = destination
  6. }
  7.  
  8. next(value) {
  9. const destination = this.destination
  10. if (destination.next && !this.isUnsubscribed) {
  11. destination.next && this.destination.next(value)
  12. }
  13. }
  14.  
  15. error(err) {
  16. const destination = this.destination
  17. if (!this.isUnsubscribed) {
  18. if (destination.error) {
  19. destination.error(err)
  20. }
  21. this.unsubscribe()
  22. }
  23. }
  24.  
  25. complete() {
  26. const destination = this.destination
  27. if (!this.isUnsubscribed) {
  28. if (destination.complete) {
  29. destination.complete()
  30. }
  31. this.unsubscribe()
  32. }
  33. }
  34.  
  35. unsubscribe() {
  36. this.isUnsubscribed = true
  37. if (this._unsubscribe) {
  38. this._unsubscribe()
  39. }
  40. }
  41. }
  42.  
  43. class Observable {
  44. constructor(_subscribe) {
  45. this._subscribe = _subscribe
  46. }
  47.  
  48. subscribe(observer) {
  49. const realDealObserver = new RealDealObserver(observer)
  50. realDealObserver._unsubscribe = this._subscribe(realDealObserver)
  51. return () => realDealObserver.unsubscribe()
  52. }
  53. }
  54.  
  55. const a = [
  56. 'Fred',
  57. 'Quentin',
  58. 'idiot',
  59. 'Doug',
  60. 'tr0n',
  61. 'James',
  62. 'Bitchface',
  63. 'Maude',
  64. 'Gladys',
  65. 'Ploppy',
  66. 'Manuel',
  67. 'Greg'
  68. ]
  69.  
  70. const observable$ = new Observable((observer) => {
  71. let i = 0
  72. const id = setInterval(() => {
  73. if (i < a.length) {
  74. observer.next(`Sup ${a[i]}`)
  75. i++
  76. } else {
  77. observer.complete()
  78. }
  79. }, 100)
  80.  
  81. return () => {
  82. console.log('Are you sure you want to unsubscribe? Kidding, unsubscribed.')
  83. clearInterval(id)
  84. }
  85. })
  86.  
  87. const observer = {
  88. next(x) { console.log('next -> ' + x)},
  89. error(err) {},
  90. complete() { console.log('We are done diddly done!')}
  91. }
  92.  
  93. const subscription$ = observable$.subscribe(observer)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement