memoize icon indicating copy to clipboard operation
memoize copied to clipboard

[Question/Request] Async functions

Open hffmnn opened this issue 2 years ago • 1 comments

Thanks a lot for this crate, works really great.

I would have one use case, that currently isn't supported: When trying to apply the macro to an async function, it doesn't compile (because the returned Future is not clonable).

A typical use case would be caching of network requests.

Currently, I have a workaround for this, but it feels rather complicated or indirect:

  1. Use a blocking client in the memoized function to do the network request
  2. call the memoized function from an async function via tokios task::spawn_blocking as described here
use memoize::memoize;
use std::{collections::HashMap, time::Duration};
use tokio::task;

#[memoize(Capacity: 5, TimeToLive: Duration::from_secs(3600))]
fn hello(query: String) -> Result<String, ()> {
    let response = reqwest::blocking::get(format!("https://some-endpoint.com/?{query}"));
    // do things with the response...
    // return 
    Ok(something_i_need.into())
}

async fn cached(query: String) -> Result<String, ()> {
    let res = task::spawn_blocking(move || hello(query)).await;
    if let Ok(res) = res {
        return res;
    }
    Err(())
}

Because I have no idea about macros I wonder if it would be possible to add a async_memoize version that calls the async (memoized) function and how much work that would be.

hffmnn avatar Aug 02 '23 15:08 hffmnn

Thank you for the detailed description. In my view, this crate is useful for very simple tasks, but doesn't intend to provide a general caching layer. If you want to cache results of network calls, it sounds too complicated for what this crate is promising, and it might be a lot easier and productive to build a custom cache layer yourself.

dermesser avatar Aug 04 '23 14:08 dermesser