I'm working on a small client-server application where clients can create or join a Room
created by another client, the server is fully async (with async-std
).
To achieve this I've created a State
struct:
use uuid::Uuid;
use std::{collections::HashMap, sync::{Arc, Weak}};
use async_std::sync::RwLock;
struct Room {
// --snip--
}
struct State {
rooms: RwLock<HashMap<Uuid, Weak<Room>>>,
// --snip--
}
I wrapped the map in an RwLock
because I need mutability to add or remove rooms, and I also wrapped the Room
in a Weak
because the rooms should be dropped once all clients (each one owns an Arc<Room>
) disconnect. A State
is created on startup and wrapped in an Arc
because I handle new connections like this: async_std::task::spawn(handle_stream(&state, stream, ..))
.
The problem is that I need to periodically iterate over the hash_map to remove the Weak
that can't be upgraded.
Is there any way to store a Weak<Room>
without periodic cleaning ?
What do you think of this approach ? How would you have done it ?