xebia-functional/fetch

Caching in readme

DenisNovac opened this issue · 2 comments

There is this example of caching at the end of readme:

def fetchTwice[F[_] : Concurrent]: Fetch[F, (String, String)] = for {
  one <- fetchString(1)
  two <- fetchString(1)
} yield (one, two)

Isn't this just a deduplication? I mean, results are not saved to the next call:

val l: Fetch[IO, (Option[String], Option[String])] = for {
    d1 <- data.fetchElem(0)
    d2 <- data.fetchElem(0)
  } yield (d1, d2)
  Fetch.run(l).unsafeRunSync()  // asks for elem 0 once
  Fetch.run(data.fetchElem(0)).unsafeRunSync()  // asks for elem 0 too, not cached?

As mentioned in the comment in the referenced issue, this is because a new cache is created each time you run a Fetch, by default. If, instead, you want to cache between requests, you should use runCache instead which returns the cache, which you can in turn pass to each subsequent Fetch request. It will then use that and properly fetch the element from the local cache.

I will create a PR to clear this up in the README so that this behavior is much more obvious.

@sloshy that is a great addition, thank you.