Explicitly Stop Subscription

297 Views Asked by At

In my Meteor application I have a publication which may or may not publish a large set of documents. Typically, the publication publishes any number of documents up to a few hundred. However, these documents are added by the user and there is no limit to how many the user can add. So, in theory (and at some point in practice) users can have several thousands, tens of thousands if not hundreds of thousands of documents that would be published using this publication.

Although I am using pagination to only display a small number of documents, the publication is a custom publication that joins the data of several collections and thus pagination, filtering as well as sorting all happen in the query:

const subscription = Meteor.subscribe('myLargePublication');
const documents = MyLargePublication.find({ query }, { skip, limit, sort });

This works fine regardless of the number of documents. However, the issue that I have is that if a user enters this view and then immediately routes to another view, all subsequent subscriptions are blocked until all data from myLargePublication was downloaded.

From the meteor documentation on #subscribe I take that there is a function stop() that can be called on the handler of a subscription to

Cancel the subscription. This will typically result in the server directing the client to remove the subscription’s data from the client’s cache.

Hence, I was hoping that using something like this may solve the issue:

componentWillUnmount() {
    const { subscription } = this.props;
    subscription.stop()
}

Looking at logs from this.onStop(() => { ... }) in my publication does not reveal any helpful insights. It appears that this function does not do anything at all in this scenario and I feel that to solve my issue, I have to change my publication/subscription.

Is there any way I can prematurely cancel a subscription from the client?

1

There are 1 best solutions below

1
On

I believe you have a design issue, yourMeteor.subscribe('myLargePublication'); can accept another augment that controls the behaviour ofMeteor.publish, so you could send in 10 documents at a time, or return a set of documents based on user search.

Needless to say, it's not reasonable to publish hundreds of documents, this will impact performance on both server / client, having said that, since you are using React, when the component unmount the subscription should stop.

There are some libraries you can check that might help in your situation

Reactive subscription (Doesn't restart subscription from the beginning when the argument passed to Meteor.publish)

Tracker - component (Stops subscription when component unmount)