Git Product home page Git Product logo

thunky's Introduction

thunky

crates.io version build status downloads

Delay the evaluation of a paramless async function and cache the result. Adapted from mafintosh/thunky

Example

Let's make a simple function that returns a random number 1 second after it is called for the first time

extern crate thunky;
extern crate rand;
use thunky::*;
use rand::Rng;

fn main () {
    let run = move |thunk: &Thunky<u32, &str>| {
        let mut rng = rand::thread_rng();
        thunk.cache(Ok(rng.gen::<u32>()));
    };

    let thunk = Thunky::new(Box::new(run));

    // I miss JavaScript's `setTimeout()`
    let thunk_clone = Arc::clone(&thunk);
    let when = Instant::now() + Duration::from_millis(1000);
    let task = Delay::new(when)
        .and_then(move |_| {
           let mut rng = rand::thread_rng();
           thunk_clone.cache(Ok(rng.gen::<u32>()));
           Ok(())
        })
        .map_err(|e| panic!("delay errored; err={:?}", e));

    thunk.run(Box::new(|arg: &Result<u32, &str>| -> () {
        println!("{}", arg.unwrap()); // prints random number
    }));

    tokio::run(task);  

    thunk.run(Box::new(|arg: &Result<u32, &str>| -> () {
        println!("{}", arg.unwrap()); // prints the same random number as above
    }));
}

Error → No caching

If the thunk cache function is called with an Err<E>, it will not cache the result

let v = Mutex::new(0);

let run = move |thunk: &Thunky<u32, &str>| {
    if *v.lock().unwrap() == 0 {
        thunk.cache(Err("not cache"))
    } else if  *v.lock().unwrap() == 1 {
        thunk.cache(Ok(100))
    }
    *v.lock().unwrap() += 1;
}

let thunk = Thunky::new(Box::new(run));

thunk.run(Box::new(|arg: &Result<u32, &str>| -> () {
    assert_eq!("not cache", arg.unwrap_err());
}))

thunk.run(Box::new(|arg: &Result<u32, &str>| -> () {
    assert_eq!(100, arg.unwrap());
}))

Installation

cargo add thunky

License

MIT OR APACHE

thunky's People

Contributors

zhouhanseng avatar

Stargazers

zbv avatar Andrejs Agejevs avatar Andrew Chou avatar 周汉成 avatar

Watchers

James Cloos avatar 周汉成 avatar

Forkers

isgasho

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.