Advertisement
Guest User

Untitled

a guest
Dec 5th, 2019
139
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. const {Subject} = require("rxjs")
  2. const {createStore} = require("redux")
  3.  
  4. function addItem(item) {
  5.     return {
  6.         type: "ADD_ITEM",
  7.         payload: item,
  8.         property: "array"
  9.     }
  10. }
  11.  
  12. const reducer = (state = {array: []}, action) => {
  13.     switch (action.type) {
  14.         case "ADD_ITEM" :
  15.             return {...state, array: [...state.array, action.payload]}
  16.         default:
  17.             return state
  18.     }
  19. }
  20.  
  21. class SubscriberService {
  22.     constructor() {
  23.         // Build non-nested structure for all observables
  24.         this.subscribeTo = {array: new Subject()}
  25.     }
  26.  
  27.     getObservable(property) {
  28.         return this.subscribeTo[property]
  29.     }
  30.  
  31.     notify(property, value) {
  32.         this.getObservable(property).next(value)
  33.     }
  34. }
  35.  
  36. const subscriberService = new SubscriberService()
  37.  
  38. class StoreService {
  39.     constructor() {
  40.         this.store = createStore(reducer)
  41.         this.subscriberService = subscriberService // Angular-Injection
  42.     }
  43.  
  44.     dispatch(action) {
  45.         this.store.dispatch(action)
  46.         this.subscriberService.notify(action.property, action.payload)
  47.     }
  48. }
  49.  
  50. const storeService = new StoreService()
  51.  
  52. const blacklistSubscriber = subscriberService.getObservable("array").subscribe((x) => {
  53.     console.log("array changed to", x)
  54. })
  55.  
  56. storeService.dispatch(addItem(1))
  57. storeService.dispatch(addItem(2))
  58.  
  59. blacklistSubscriber.unsubscribe()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement