Skip to content

spawning a task referencing self with anonymous lifetime #3362

Answered by Darksonn
barkanido asked this question in Q&A
Discussion options

You must be logged in to vote

This is due to Rust's single-ownership principle. To give the new task ownership of the ClicksConsumer, that task must be the only place that can access it, however the start method takes &self, which means that start only has borrowed access to the ClickConsumer. Since start does not have ownership, it cannot give away ownership to the new task.

One approach is to change start to take ownership of self. This looks like the following:

pub async fn start(self) {
    tokio::spawn(async move {
        let stream = self.consumer.start();
        stream.try_for_each(|burrwed_msg| {
            let message = burrwed_msg.detach();
            async move {
                self.tx.send(Click {});

Replies: 1 comment

Comment options

You must be logged in to vote
0 replies
Answer selected by barkanido
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants