tc39 / proposal-observable

Observables for ECMAScript
https://tc39.github.io/proposal-observable/
3.06k stars 90 forks source link

Arguments passed to subscribe - pass through to constructor fn? #188

Open bradennapier opened 6 years ago

bradennapier commented 6 years ago

First - Love the proposal! I was just playing with it a bit and can't wait for this to be implemented.

This may have been brought up already but my quick search didn't bring anything. Perhaps this is breaking some major concept or something but my first thought with this is that we end up with a situation that it would be nice to receive pass-through parameters when subscribing to an observable.

Below is probably not exactly correct as I didn't check the syntax to make sure what im doing even works with the keydown api but it gives the general idea:

(I also know that this specific example makes no sense but i wanted to keep with the example in the docs so people didn't have to infer what is happening -- my example need is for a redux-like connect where we have a single params given then each "subscriber" would pass the component to reference)

export default function subscribe(eventName) {
  return new Observable((observer, keys) => {
    // Create an event handler which sends data to the sink
    const handler = event => keys.some(key => event.key === key) && observer.next(event);

    // Attach the event handler
    element.addEventListener(eventName, handler, true);

    // Return a cleanup function which will cancel the event stream
    return () => {
      // Detach the event handler from the element
      element.removeEventListener(eventName, handler, true);
    };
  });
}

const subscriber = subscribe('keydown');

subscriber.subscribe(
  {
    next: evt => {},
  },
  ['a'],
);

where

interface ExtendedSubscriber {
    subscriber(Observer, ...args: Array<any>) 
}

Just thinking it helps make observable more composable and ends up not requiring the wrapping function in many situations. It shouldn't really make much of a different in the implementation I would think to do it this way unless I am missing something.

Feels like this is also a way that the user can compose their own map and other functionality in a fairly straight forward and clean way.