re-rxjs / react-rxjs

React bindings for RxJS
https://react-rxjs.org
MIT License
553 stars 20 forks source link

handling subscriptions reactively #110

Closed josepot closed 4 years ago

josepot commented 4 years ago

I've been thinking a lot about #101 lately and I really think that we should do a better job at being explicit about how we think that those subscriptions should be handled.

It's easy for me and for @voliva to know what's safe and what's not, because we understand what are the internals and the implications of misusing bind. However, we need to find a better way to setup our users for success.

That's why I think that we should promote a pattern of reactive top-level subscriptions (kinda like a router) that ensures that when a hook generated from bind is consumed, the subscription is already there. And also, that the subscription will be disposed once it's no longer needed. Also, this practice would be aligned with what the React team proposes for data-fetching: the requests should start before render.

In order to do that, though. It's necessary to make an important change to the "shared-observable" that's exposed from bind: that observable should not complete, otherwise it will be too complicated for the consumers to use this library safely.

I will be posting updates on this issue, but I don't think that we can go life with react-rxjs.org until we haven't figured this out properly.

josepot commented 4 years ago

After having put a lot of thought into this, I think that the approach that we are promoting on the "Github Issues Viewer" should be one of the recommended ways of approaching this. There are nuances, of course, but overall I think that's the most straightforward CM compliant way to approach this.

In a nutshell our recommendation should consist in creating top-level subscriptions that listen to a stream that indicates whether that component is going to be used, and perform a switchMap so that if the component is not going to be used it returns EMPTY and if it's going to be used it returns the observable(s) that are going to be consumed inside the component.

There are other cases, of course, like when you have a subscription that can only start after a user-action (submit-form, etc), in that case a basic useSubscribe would suffice. That's why I'm planing to add a section that explains these different cases in detail. However, the point that we are making in the docs is pretty clear and CM compliant: those subscriptions should exist before React attempts to use his.