深圳scala-meetup-20180902(2)- Future vs Task and ReaderMonad依赖注入
在对上一次3月份的scala-meetup里我曾分享了关于Future在函数组合中的问题及如何用Monix.Task来替代。具体分析可以查阅这篇博文。在上篇示范里我们使用了Future来实现某种non-blocking数据库操作,现在可以用Task替换Future部分:
class KVStore[K,V] {
private val kvs = new ConcurrentHashMap[K,V]()
def create(k: K, v: V): Task[Unit] = Task.delay(kvs.putIfAbsent(k,v))
def read(k: K): Task[Option[V]] = Task.delay(Option(kvs.get(k)))
def update(k: K, v: V): Task[Unit] = Task.delay(kvs.put(k,v))
def delete(k: K): Task[Boolean] = Task.delay(kvs.remove(k) != null)
}
Task是一个真正的Monad,我们可以放心的用来实现函数组合:
type FoodName = String
type Quantity = Int
type FoodStore = KVStore[String,Int] def addFood(food: FoodName, qty: Quantity)(implicit fs: FoodStore): Task[Quantity] = for {
current <- fs.read(food)
newQty = current.map(cq => cq + qty).getOrElse(qty)
_ <- fs.update(food,newQty)
} yield newQty def takeFood(food: FoodName, qty: Quantity)(implicit fs: FoodStore): Task[Quantity] = for {
current <- fs.read(food)
cq = current.getOrElse()
taken = Math.min(cq,qty)
left = cq - taken
_ <- if(left > ) fs.update(food,left) else fs.delete(food)
} yield taken def cookSauce(qty: Quantity)(get: (FoodName,Quantity) => Task[Quantity],
put: (FoodName,Quantity) => Task[Quantity]): Task[Quantity] = for {
tomato <- get("Tomato",qty)
vaggies <- get("Veggies",qty)
_ <- get("Galic",)
sauceQ = tomato/ + vaggies * /
_ <- put("Sauce",sauceQ)
} yield sauceQ def cookPasta(qty: Quantity)(get: (FoodName,Quantity) => Task[Quantity],
put: (FoodName,Quantity) => Task[Quantity]): Task[Quantity] = for {
pasta <- get("Pasta", qty)
sauce <- get("Sauce", qty)
_ <- get("Spice", )
portions = Math.min(pasta, sauce)
_ <- put("Meal", portions)
} yield portions
跟上次我们使用Future时的方式没有两样。值得研究的是如何获取Task运算结果,及如何更精确的控制Task运算如取消运行中的Task:
implicit val refridge = new FoodStore
val shopping: Task[Unit] = for {
_ <- addFood("Tomato",)
_ <- addFood("Veggies",)
_ <- addFood("Garlic", )
_ <- addFood("Spice", )
_ <- addFood("Pasta", )
} yield()
val cooking: Task[Quantity] = for {
_ <- shopping
sauce <- cookSauce()(takeFood(_,_),addFood(_,_))
meals <- cookPasta()(takeFood(_,_),addFood(_,_))
} yield meals
import scala.util._
import monix.execution.Scheduler.Implicits.global
val cancellableCooking = Cooking.runOnComplete { result =>
result match {
case Success(meals) => println(s"we have $meals pasta meals for the day.")
case Failure(err) => println(s"cooking trouble: ${err.getMessage}")
}
}
global.scheduleOnce( second) {
println(s"its taking too long, cancelling cooking ...")
cancellableCooking.cancel()
}
在上面例子里的addFood,takeFood函数中都有个fs:FoodStore参数。这样做可以使函数更加通用,可以对用不同方式实施的FoodStore进行操作。这里FoodStore就是函数的依赖,我们是通过函数参数来传递这个依赖的。重新组织一下代码使这种关系更明显:
class Refridge {
def addFood(food: FoodName, qty: Quantity): FoodStore => Task[Quantity] = { foodStore =>
for {
current <- foodStore.read(food)
newQty = current.map(c => c + qty).getOrElse(qty)
_ <- foodStore.update(food, newQty)
} yield newQty
}
def takeFood(food: FoodName, qty: Quantity): FoodStore => Task[Quantity] = { foodStore =>
for {
current <- foodStore.read(food)
cq = current.getOrElse()
taken = Math.min(cq, qty)
left = cq - taken
_ <- if (left > ) foodStore.update(food, left) else foodStore.delete(food)
} yield taken
}
}
现在我们用一个函数类型的结果来代表依赖注入。这样做的好处是简化了函数主体,彻底把依赖与函数进行了分割,使用函数时不必考虑依赖。
scala的函数式组件库cats提供了一个Kleisli类型,reader monad就是从它推导出来的:
final case class Kleisli[M[_], A, B](run: A => M[B]) { self =>
...
trait KleisliFunctions {
/**Construct a Kleisli from a Function1 */
def kleisli[M[_], A, B](f: A => M[B]): Kleisli[M, A, B] = Kleisli(f)
…
def >=>[C](k: Kleisli[M, B, C])(implicit b: Bind[M]): Kleisli[M, A, C] =
kleisli((a: A) => b.bind(this(a))(k.run))
…
Kleisli的用途就是进行函数的转换
// (A=>M[B]) >=> (B=>M[C]) >=> (C=>M[D]) = M[D]
实际上Kleisli就是ReaderT:
type ReaderT[F[_], E, A] = Kleisli[F, E, A]
val ReaderT = Kleisli
val reader = ReaderT[F,B,A](A => F[B])
val readerTask = ReaderT[Task,B,A](A => Task[B])
val injection = ReaderT { foodStore => Task.delay { foodStore.takeFood } }
val food = injection.run(db) // run(kvs), run(dbConfig) …
这段代码里我们也针对上面的例子示范了ReaderT的用法。现在我们可以把例子改成下面这样:
type FoodName = String
type Quantity = Int
type FoodStore = KVStore[String,Int] class Refridge {
def addFood(food: FoodName, qty: Quantity): ReaderT[Task,FoodStore,Quantity] = ReaderT{ foodStore =>
for {
current <- foodStore.read(food)
newQty = current.map(c => c + qty).getOrElse(qty)
_ <- foodStore.update(food, newQty)
} yield newQty
} def takeFood(food: FoodName, qty: Quantity): ReaderT[Task,FoodStore,Quantity] = ReaderT{ foodStore =>
for {
current <- foodStore.read(food)
cq = current.getOrElse()
taken = Math.min(cq, qty)
left = cq - taken
_ <- if (left > ) foodStore.update(food, left) else foodStore.delete(food)
} yield taken
} }
ReaderT[F[_],E,A]就是ReaderT[Task,FoodStore,Quantity]. FoodStore是注入的依赖,ReaderT.run返回Task:
val cooking: ReaderT[Task,FoodStore,Quantity] = for {
_ <- shopping
sauce <- cooker.cookSauce()
pasta <- cooker.cookPasta()
} yield pasta
import scala.concurrent.duration._
import scala.util._
import monix.execution.Scheduler.Implicits.global
val timedCooking = cooking.run(foodStore).timeoutTo( seconds, Task.raiseError( new RuntimeException(
"oh no, take too long to cook ...")))
val cancellableCooking = timedCooking.runOnComplete { result =>
result match {
case Success(meals) => println(s"we have $meals specials for the day.")
case Failure(exception) => println(s"kitchen problem! ${exception.getMessage}")
}
}
global.scheduleOnce( seconds) {
println("3 seconds passed,cancelling ...")
cancellableCooking.cancel()
}
我们知道cooking是个ReaderT,用run(foodStore)来注入依赖foodStore。那么如果我们还有一个kvStore或者jdbcDB,mongoDB可以直接用run(kvStore), run(jdbcDB), run(mongoDB) ... 返回的结果都是Task。
深圳scala-meetup-20180902(2)- Future vs Task and ReaderMonad依赖注入的更多相关文章
- dotnet core在Task中使用依赖注入的Service/EFContext
C#:在Task中使用依赖注入的Service/EFContext dotnet core时代,依赖注入基本已经成为标配了,这就不多说了. 前几天在做某个功能的时候遇到在Task中使用EF DbCon ...
- Scala依赖注入
控制反转(Inversion of Control,简称IoC),是面向对象编程中的一种设计原则,可以用来降低计算机代码之间的耦合程度.其中最常见的方式叫做依赖注入(Dependency Inject ...
- asyncio模块中的Future和Task
task是可以理解为单个coroutine,经过ensure_future方法处理而形成,而众多task所组成的集合经过asyncio.gather处理而形成一个future. 再不精确的粗略的说 ...
- 深圳scala-meetup-20180902(1)- Monadic 编程风格
刚完成了9月份深圳scala-meetup,趁刮台风有空,把我在meetup里的分享在这里发表一下.我这次的分享主要分三个主题:“Monadic编程风格“.”Future vs Task and Re ...
- PICE(1):Programming In Clustered Environment - 集群环境内编程模式
首先声明:标题上的所谓编程模式是我个人考虑在集群环境下跨节点(jvm)的流程控制编程模式,纯粹按实际需要构想,没什么理论支持.在5月份的深圳scala meetup上我分享了有关集群环境下的编程模式思 ...
- SDP(13): Scala.Future - far from completion,绝不能用来做甩手掌柜
在前面几篇关于数据库引擎的讨论里很多的运算函数都返回了scala.Future类型的结果,因为我以为这样就可以很方便的实现了non-blocking效果.无论任何复杂的数据处理操作,只要把它们包在一个 ...
- PYTHON ASYNCIO: FUTURE, TASK AND THE EVENT LOOP
from :http://masnun.com/2015/11/20/python-asyncio-future-task-and-the-event-loop.html Event Loop On ...
- 参加完Rocket MQ Meetup深圳站,回顾和想法
最近一段时间才开始关注云栖社区的公众号,在两周前看到要在深圳科兴科学园办一场Rocket MQ的Meetup.因为从来没有参加过这种线下活动,而且对Rocket MQ比较感兴趣,所以就立即报名参加. ...
- Scalaz(44)- concurrency :scalaz Future,尚不完整的多线程类型
scala已经配备了自身的Future类.我们先举个例子来了解scala Future的具体操作: import scala.concurrent._ import ExecutionContext. ...
随机推荐
- C# 封装SqlHelper
在项目配置文件中添加数据库连接字符串 <connectionStrings> <add connectionString="Data Source=主机;Initial C ...
- # 20175213 2018-2019-2 《Java程序设计》第1周学习总结
在本周的java学习中,我收获了很多也遇到了很多的困难1.在寒假的预学习中,因为没能完全的安好虚拟机,导致在本周的学习一开始,虚拟机就崩溃了,所以又重新开始重头安装虚拟机.但因为网速等各种问题,虚拟机 ...
- MFC笔记8
1.在循环使用数组时需要清理数组 CString str; memset(str,0,strlen(str)); 判断两个字符串包含数字大小是否相等 CString str="22" ...
- Swagger注解
swagger注解说明 1.与模型相关的注解,用在bean上面 @ApiModel:用在bean上,对模型类做注释: @ApiModelProperty:用在属性上,对属性做注释 2.与接口相关的注 ...
- linux grep (linux查找关键字在php出现的次数)
http://www.th7.cn/system/lin/201508/127681.shtml 查找CleverCode在当前目录以及子目录,所有的php出现大于0的次数. # find -type ...
- 20162322 朱娅霖 作业011 Hash
20162322 2017-2018-1 <程序设计与数据结构>第十一周学习总结 教材学习内容总结 哈希方法 一.定义 哈希:次序--更具体来说是项在集合中的位置--由所保存元素值的某个函 ...
- Handler实现消息的定时发送
话不多说,直接上代码 private Handler mHandler = new Handler() { @Override public void handleMessage(Message ms ...
- POJ-2533.Longest Ordered Subsequence (LIS模版题)
本题大意:和LIS一样 本题思路:用dp[ i ]保存前 i 个数中的最长递增序列的长度,则可以得出状态转移方程dp[ i ] = max(dp[ j ] + 1)(j < i) 参考代码: # ...
- oracle 新增并返回新增的主键
oracle 的insert into 语句需要返回新增的主键的时候,可以使用一下insert 语法: insert into ims.t_bank_inquire_results (t_date,l ...
- 动态添加 SqlParameter 参数
List<SqlParameter> paras = new List<SqlParameter>(); paras.Add(new SqlParameter("@m ...