kefirjs / kefir

A Reactive Programming library for JavaScript
https://kefirjs.github.io/kefir/
MIT License
1.87k stars 97 forks source link

Should onValue return a function to unsubscribe? #66

Closed dzdrazil closed 9 years ago

dzdrazil commented 9 years ago

I realize this is a breaking change, and that it's entirely possible my use-case isn't quite in-line with what I should be doing (read: I'm a newb at this style of programming!).

However, I don't really see the utility of onValue being a chainable interface- wouldn't most of the desirable use-cases for it be better suited by tap instead? (discounting that tap doesn't subscribe)

I guess what I'm really looking for is an easier way to use ES6 style lambdas to subscribe to streams in my view components. E.g. I have a stream that's shared by multiple views- when the view mounts, I attach an onValue, and when a view unmounts, I need to unsubscribe so the stream isn't active anymore. take and takeWhile don't really seem to fit that use-case, and lambdas don't have names, so offValue isn't really an option either.

My proposed change would let me do something along the lines of:

/// ...
// view setup
componentDidMount() {
  this.offStream = MyStream
    .onValue(e => this.setState({data:e});
},
// view teardown
componentWillUnmount() {
  this.offStream();
}
/// ...

Am I missing something obvious? Does this make sense for how Kefir ought to be used? Or is there a valid reason for onValue to keep the current fluent interface that I'm not appreciating?

rpominov commented 9 years ago

Well, there is numbers of reasons to do and not to do this. All of them not very strong. I'd just define a helper function for your use case:

Kefir.Observable.prototype.onValue2 = function(fn) {
  this.onValue(fn);
  var _this = this;
  return function() {
    _this.offValue(fn);
  };
}