How to handle sending events in async libraries?

So, I am currently working on a library, and am looking to make it as idiomatic and clean as possible.

I want to receive events from an outside websocket API, and send them over to my library's users. Currently, I do this by having a single "handler" trait that end users implement, that allows them to override specific event handling functions to their needs. But the internal implementation is a complete mess, and I am not sure if that way of doing things are particularly Rust-y.

In particular, I require the following:

  • Mutable borrow to the "dispatcher" (or "client", in my implementation linked below) object, required for sending responses back to the 3rd party API.
  • Mutable borrow to "self", to give flexibility to the end users.
  • async/.await support (Currently using async-trait for that)

My current implementation is available here

p.s: I might be approaching this from completely the wrong perspective. In that case, please let me know of a better way!

Could you elaborate on the requirements for a better solution?
I'm unsure where users of your library inject their control flow.

Could you use simple callbacks?
Do you have a single callback?
If not, could you use a Builder pattern, to construct an object containing all callbacks that are required?

Could you elaborate on why the mutable borrows are required? What sort of flexibility is added by having a mutable borrow?

Users register their own event handlers with Discord::register_event (doc comment out of date, you don't need to specify which event to register anymore)

If you're saying simple closures, async/.await ruins this unless I use nightly or wait until async closures get stabilized.

If you're talking about event handlers, currently, I can have multiple registered (In theory, didn't test it). But that's not a general requirement.

I cannot, because async/.await totally messes with storing callbacks & async closures aren't there yet. (Assuming I understood your question correctly)

Users need a mutable borrow for the client to be able to write to the current connection, and they need a mutable borrow to modify their own internal state.

I made something with pattern matching here. Since implementing this was a breeze, I'm assuming this is the idiomatic way. Does anyone else have any recommendations?

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.