Proper way to close Change Stream Mongo db with SocketIO - Flask

Viewed 112

My goal is to listen changes in real time on the current user Object while it is online, that works at scale.

I have this piece of code :

@socket.on('listen_user')
def listen(uid):
    print(f"Listening to user : {uid}", flush=True)
    stream = db.listen_user(uid)  # Here is the Change Stream
    for change in stream:
        socket.emit("listen_user_callback", change)
    

@app.route('/users/<uid>/stop', methods=["GET"])
def stop_listener(uid):
    print(f"Stop listening to user : {uid}", flush=True)
    # TODO : Stop the previously added Change Stream (above)

And i want to do what is written in the TODO.

The question behind this is : How to handle (multiple) mongodb Change Streams and be able to properly close them all once the client disconnects ?

My above code is working to listen changes but i am not able to close the proper stream. I would like to avoid storing a map with the current opened streams server-side for memory issues.

0 Answers
Related