Fix possible memory leak in `stopListening`, refactor