Learning Reactive Programming with RxJS

Resources

Angular Services

I really like the way Angular defines services, here is an example of what I mean:

// services/message.service.js

import { BehaviorSubject } from "rxjs";

const messages = new BehaviorSubject([]);

// Export the service
// This is the public API
export default {
  getMessages: () => messages.asObservable(),
  setMessages: (msgs) => messages.next(msgs)
}

The service can be used as follows:

import MessageService from "./services/message.service";

MessageService.getMessages().subscribe((msgs) => console.log(msgs));

MessageService.setMessages(["Hello", "World"]);

Simple Redux Store

Below is a way to implement a simple Redux like store with RxJS

import { BehaviorSubject } from "rxjs";

class Store {
  state = new BehaviorSubject({});
  
  constructor(initialState) {
    this.state.next(initialState);
  }
  
  setState(newState) {
    // Merge the state
    this.state.next({...this.state.value, ...newState});
  }
  
  subscribe() {
    return this.state.subscribe;
  }
}