如何在 scala cats 中使用标志进行间隔操作

问题描述 投票:0回答:2

如果

flag
设置为 true,我需要按时间间隔运行 IO 操作。可以在一个时间间隔内从程序的其他位置多次将标志设置为 true。例如:

class IntervalAction {
  def touch: IO[Unit] // set flag to true
  
  // if flag is true, on interval do action and set flag to false
} 

class Service(action: IntervalAction) {

  def run = {
    1 to 100 traverse { i =>
      if (i % 2 == 0) action.touch()
    }
  }
}

如何使用cat 实现IntervalAction 内部调度程序、间隔处理程序、异步标志处理程序等?

scala scala-cats
2个回答
1
投票

你的代码几乎是正确的,我们只需要告诉它当条件为假时该怎么做:

1 to 100 traverse { i =>
  if (i % 2 == 0) action.touch()
  else IO.unit
}

或者使用更方便的方法:

1 to 100 traverse { i =>
  IO.whenA(i % 2 == 0)(action.touch())
}

0
投票

我带着这个解决方案

  def backgroundTest: IO[Unit] = {
    var flag = false // probably ok that it is thread-unsafe

    def backgroundInterval: IO[Unit] = {
      IO.println("Interval started") *>
        IO.sleep(3.seconds).flatMap { _ =>
          println(s"3 seconds elapsed flag is: ${flag}")
          flag = false
          backgroundInterval
        }.void
    }
    
    def innerRequestHandler: IO[Unit] = {
      for {
        _ <- Console[IO].println("Write something")
        _ <- Console[IO].readLine
          .flatMap { line =>
            if (line == "q") IO.unit
            else {
              flag = true
              innerRequestHandler
            }
          }
      } yield ()
    }

    backgroundInterval.background.use { _ =>
      innerRequestHandler
    }
  }
© www.soinside.com 2019 - 2024. All rights reserved.