Idiomatic way to have child objects notify parents

I have a parent struct that creates child structs which independently receive events. These children need to inform the parent of these events so the parent can mutate itself and potential modify the list of children.

I can't quite figure out the right way of structuring this, specifically the notification from child to parent.

I've tried a simple callback method being passed from parent to child but this seems to end up in a bit of a lifecycle hell and from my research doesn't seem idiomatic at all.

I've also thought of implementing a trait on parent and pass this to the children. I've had trouble getting this to compile also and again, doesn't seem to be idiomatic.

I'm looking for some inspiration/advice for this kind of pattern. Should this even be a thing? Is it better to try and keep all handling in the parent itself and remove the children (difficult to answer without more details).

The parent could keep the receiver of a std::sync::mpsc channel and give clones of the sender to all its children. You’d need to have the parent poll for unprocessed events occasionally, though.

Alternatively, you could store everything in an Arc<Mutex<…>> and let the children have a Weak pointer to their parent than can be upgraded whenever a notification needs to be sent.

There are probably also other ways, but they’ll likely all be cumbersome like these— This isn’t a pattern that fits particularly well with Rust’s ownership system.

2 Likes

I ended up just re-architecting it so I didn’t need to pass events back up to the parent at all.