Scalaz中Task和IO之间有什么区别? [英] What's the difference between Task and IO in Scalaz?

查看:158
本文介绍了Scalaz中Task和IO之间有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这两种Scalaz类型

These two Scalaz types

  • scalaz.concurrent.Task[+A]
  • scalaz.effect.IO[A]

似乎在概念上非常相似。他们俩:

seem very conceptually similar. They both:


  • 代表潜在的副作用计算

  • 产生成功( A )或失败(异常)结果

  • 拥有 Monad instances

  • 可以用运行 unsafePerformIO

  • Represent a potentially side-effecting computation
  • Produce a success (A) or failure (Exception) result
  • Have Monad instances
  • Can be unsafely unwrapped with run or unsafePerformIO

它们有何不同?为什么它们都存在?

How do they differ? Why do they both exist?

推荐答案

核心区别在于IO只是延迟了某些事情的执行但是在当前线程中执行了。另一方面,任务能够同时执行某些操作(因此是隐式的ExecutorService)。

Core difference is that IO simply delays the execution of something but does it within a current thread. Task on the other hand is capable of executing something concurrently (thus the implicit ExecutorService).

此外,Task还带有scalaz Future的语义(Future比经典的scala版本更具有可比性; Future允许你通过明确分叉来更好地控制并发性一旦实例化,就定义并不执行并行执行任务。此外,如果你阅读scalaz的Future的源代码,它会指向Task作为一个更强大的版本,可以在prod中使用。

Additionally, Task carries the semantics of scalaz's Future (Future that is more compossible than the classic scala version; Future that allows you to have higher control of concurrency by making forking explicitly defined and not execute tasks in parallel as soon as instantiated ). Furthermore, if you read the source for scalaz's Future it will point you to Task as a more robust version that can be used in prod.

最后,请注意,任务的attemptRun返回 \ / [Throwable,A] ,而IO的unsafePerformIO只返回 A 即可。这说明了对现实生活中错误场景的更强有力的处理。

Finally, note that attemptRun of the Task returns \/[Throwable, A] while unsafePerformIO of IO just returns A. This speaks to more robust treatment of real life error scenarios.

据我所知,无论你在哪里使用IO来组合效果,你都会在实际生产代码库中使用Task。

As far as I know, everywhere you would use IO to compose effects you would use Task in real production codebase.

这是一篇关于任务使用的好文章: Tim Perrett的任务帖子

Here is a good blog post about Task usage: Tim Perrett's Task Post

这篇关于Scalaz中Task和IO之间有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆