dtolnay / async-trait

Type erasure for async trait methods
Apache License 2.0
1.81k stars 84 forks source link

Accessing a Context #116

Closed AljoschaMeyer closed 4 years ago

AljoschaMeyer commented 4 years ago

Is there some elegant way of implementing an async trait where the implementation of some of the methods requires access to the Context in which the returned future is run, e.g. to park a task? The best I can come up with is doing an impl without the macro, but that will involve relying on a number of implementation details of this crate (and a minor annoyance is losing the convenience for those methods that do not need access to a Context).

AljoschaMeyer commented 4 years ago

Or perhaps a more general way of phrasing this: Suppose I have a way of creating values of type Foo implements Future<Bar>, how can I leverage this for the implementation of an async trait method of signature async fn (&self) -> Bar?

dtolnay commented 4 years ago

Suppose I have a way of creating values of type Foo implements Future<Bar>, how can I leverage this for the implementation of an async trait method of signature async fn (&self) -> Bar?

It's possible I am misunderstanding but it sounds like you are asking how to invoke a Future impl from an async fn in a trait.

.await does that.

#[async_trait]
impl MyTrait for Struct {
    async fn f(&self) -> Bar {
        make_foo().await;
    }
}

where make_foo produces Foo which implements Future\<Bar>.

AljoschaMeyer commented 4 years ago

I suddenly feel very stupid. Thanks 😄