Function cooperative

Source
pub fn cooperative<F: Future>(fut: F) -> Coop<F> 
Expand description

Creates a wrapper future that makes the inner future cooperate with the Tokio scheduler.

When polled, the wrapper will first call poll_proceed to consume task budget, and immediately yield if the budget has been depleted. If budget was available, the inner future is polled. The budget consumption will be made final using RestoreOnPending::made_progress if the inner future resolves to its final value.

§Examples

When you call recv on the Receiver of a tokio::sync::mpsc channel, task budget will automatically be consumed when the next value is returned. This makes tasks that use Tokio mpsc channels automatically cooperative.

If you’re using futures::channel::mpsc instead, automatic task budget consumption will not happen. This example shows how can use cooperative to make futures::channel::mpsc channels cooperate with the scheduler in the same way Tokio channels do.

use tokio::task::coop::cooperative;
use futures::channel::mpsc::Receiver;
use futures::stream::StreamExt;

async fn receive_next<T>(receiver: &mut Receiver<T>) -> Option<T> {
    // Use `StreamExt::next` to obtain a `Future` that resolves to the next value
    let recv_future = receiver.next();
    // Wrap it a cooperative wrapper
    let coop_future = cooperative(recv_future);
    // And await
    coop_future.await
}