Search code examples
scalascala-cats

How can I make interval action with flag in scala cats


I need to run IO action on interval if flag is set to true. Flag could be set to true multiple times during one interval from other places of program. For example:

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()
    }
  }
}

How can I implement IntervalAction inner scheduler, interval handler, async flag handler etc with cats?


Solution

  • I come with this solution

      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 {
            _ <- IO.println("Write something")
            _ <- IO.readLine
              .flatMap { line =>
                if (line == "q") IO.unit
                else {
                  flag = true
                  innerRequestHandler
                }
              }
          } yield ()
        }
    
        backgroundInterval.background.use { _ =>
          innerRequestHandler
        }
      }