1

Anybody know how I could make an RxJS observable without RxJS?
I'm working on a library and I need it to be small (So including RxJS isn't really viable), run in the browser (IDK if Browserify will work for RxJS), and be fast. I need a way for a given element to 'listen' (or in RxJS terms, 'subscribe') to a value and update its text content whenever the value changes.
My current implementation is just a interval loop that checks if the previous value is the same as the current one, and if it isn't, it modifies the DOM.

Comments
  • 2
    Rxjs is treeshaking optimized to a high degree, so it can be used in those situations. Building your own is a good exercise though.

    Step 1: learn the observer pattern
    https://en.m.wikipedia.org/wiki/...

    Step 2: read the Observable and Subscription classes (and first degree indirect subclasses/dependencies

    That's a start. Outside of that, it's just down to determine if you want to go down the FP path, or build imperative pub/sub.
  • 0
    @SortOfTested Ah yes, the good old observer pattern.
  • 0
    @SortOfTested I think I've managed to make one? Is there anything obvious that might go awry with this or nah?

    https://bit.ly/2RO433x (TypeScript playground)
  • 1
    Looks great for a first draft 🙂

    Few issues you'll into at runtime:
    - Might encounter memory leaks/null exceptions if you spread the subscribers around the application as there's not really any code to handle subscriber collection
    - newing the subscribers may be a little untuitive to users

    What you've implemented here is closer to Subject in terms of functionality (producer and subscribable). That's also probably what you want in a simple scenario like this as you don't have to have async producers or finite sequences encapsulated from go. I've put together a quick functional demo that cleans this process up a bit, hopefully explains it a little better as well:

    https://bit.ly/3aRZlui
  • 1
    @SortOfTested Ah alright, so you create the Subject class on top of the Observable interface so that you can manage the subscriptions independently from the Subject?

    Thanks for the example!
  • 1
    Yep, and no prob. Subject is an observable typographically. It provides the additional next function to send data long to subscribers. The "asObservable" feature is type narrowing so you can hand it to other parts of your application safely and retain sole ownership of calling next.
Add Comment