4

There are two ways to subscribe/watch to logs/events:

Subscribe:

var subscription = web3.eth.subscribe('logs', {
    address: '0x123456..',
    topics: ['0x12345...']
}, function(error, result){
    if (!error)
        console.log(log);
});

Unsubscribe:

subscription.unsubscribe(function(error, success){
    if(success)
        console.log('Successfully unsubscribed!');
});

But how do I unsubscribe if I watch the logs / events like this:

myContractWebsocket.events.MyLogName({
    filter: {'orderId': '0x123456...'}, 
    fromBlock: 0
    })
    .on('data', data => { console.log(data); })
    .on('error', error => { console.log(error); });

2 Answers 2

1

Struggled with this as well, here is my solution:

Event Setup

let subscriptionId;
const eventEmitter = web3.contract.events.MyEvent({...options})
   .on('connected', id => subscriptionId = id)
   .on('data', event => {
      // Your event logic
    })

Unsubscribe

// Unsubscribe if connected successfully and not undefined
if(!subscriptionId) return
eventEmitter.options.requestManager.removeSubscription(subscriptionId)
0

myContractWebsocket.events.MyLogName returns a Subscription response, which has an unsubscribe method. See here for a bit more detail.

2
  • Unfortunately it doesn't work like that. I get TypeError: subscription.unsubscribe is not a function
    – Rob Magier
    Commented Feb 17, 2019 at 18:26
  • @RobMagier could you add the code from attempting this answer, along with the error, into the question? Commented Jan 7, 2021 at 10:41

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.