'Can I clone a future?

I want to write some generic retry logic for a future.

I know the concrete return type and want to retry the same future.

My code only has access to the future - I do not want to wrap every fn call site in a closure to enable recreating it.

It seems that a "future" is a combination of (fn, args), and when .await is called, it runs and waits for the result in place.

If I am able to clone all of the args, would it be possible to create a clone of the not-started future to retry it if it fails the first time?



Solution 1:[1]

A Future can be cloned via https://docs.rs/futures/latest/futures/future/trait.FutureExt.html#method.shared. This is useful to pass the future to multiple consumers, but not suitable for retry.

To have retries with Futures, you need some kind of Future factory, to create a new Future for a retry when an error occurs. Ideally this retry mechanism would be wrapped in its own Future, to hide the complexity for consumers.

There's a crate which does that already: https://docs.rs/futures-retry/latest/futures_retry/struct.FutureRetry.html

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Pascalius