English 中文(简体)
• 如何在Schala Cats/FS2中作出可贵的排外回击?
原标题:How to make cancellable timeout callback in Scala Cats / FS2?

我希望,用户能够花一个时间回击,能够取消。 与此类似:

def main: F[Unit] =
  for
    cancel       <- runTimer(callback, 5.seconds)
    shouldCancel <- askUser
    _            <- cancel.whenA(shouldCancel)
  yield ()

我怎么能以FS2的类别来做?

问题回答

由于cats-effect在解决一致问题时具有非常强的威力,你需要的守则实际上非常简单:

def runTimer(
  callback: IO[Unit],
  delay: Duration,
  cancel: IO[Unit]
): IO[Unit] =
  IO.race(
    IO.sleep(delay) >> callback.uncancelable,
    cancel
  ).void

主要方面如下:

  • Using IO.sleep to delay the execution of the callback.
  • Using uncancelable to make the callback uncancelable.
  • Using IO.race to run both the delayed callback and the cancel concurrently. If the cancel completes before the delay, the race will cancel the execution of the callback.

您可以改进这项工作,以确保<代码>cancel>可取消<编码> 查询背书/代码>,但允许在上一级取消整个<代码><<>race>/code>。






相关问题
How to flatten a List of different types in Scala?

I have 4 elements:List[List[Object]] (Objects are different in each element) that I want to zip so that I can have a List[List[obj1],List[obj2],List[obj3],List[obj4]] I tried to zip them and I ...

To use or not to use Scala for new Java projects? [closed]

I m impressed with Twitter and investigating to use Scala for a new large scale web project with Hibernate and Wicket. What do you think about Scala, and should I use it instead of Java? EDIT: And, ...

Why does Scala create a ~/tmp directory when I run a script?

When I execute a Scala script from the command line, a directory named "tmp" is created in my home directory. It is always empty, so I simply deleted it without any apparent problem. Of course, when I ...

Include jar file in Scala interpreter

Is it possible to include a jar file run running the Scala interpreter? My code is working when I compile from scalac: scalac script.scala -classpath *.jar But I would like to be able to include a ...

Scala and tail recursion

There are various answers on Stack Overflow which explain the conditions under which tail recursion is possible in Scala. I understand the limitations and how and where I can take advantage of tail ...

热门标签