badeleux
badeleux

Reputation: 592

Future with State monad

I would like to use State monad to implement caching for data provided from third party API. Let's imagine method getThirdPartyData(key: String) which firstly checks cache then if it's not present there should make request to API. First and most naive implementation which came to my mind was enclosing State type within Future -

Future[State[Cache, ThirdPartyData]]

But it's not correct because when request fails you will lose your cache (getThirdPartyData will return Failure).

Second option which came to my mind was to extend, or rather redefine State monad - s => Future[(s,a)], instead of s => (s,a), but I thought that it's quite popular problem so scalaz probably has some already defined way to solve this issue.

Any help greatly appreciated!

Upvotes: 5

Views: 626

Answers (1)

sungiant
sungiant

Reputation: 3222

Is this what you are looking for StateT[Future, Cache, ThirdPartyData]?

implicit val m: Monoid[ThirdPartyData] = ...
val startState: Cache = ...
val l: List[StateT[Future, Cache, ThirdPartyData]] = ...

val result = l.sequenceU
 .map { _.foldMap (identity)) }
 .eval (startState)

Upvotes: 6

Related Questions