Search code examples
scalascala-catsmonixcats-effect

Collecting data from all tasks executed on monix Scheduler


I'm using Monix Scheduler to execute some tasks periodically. But I don't know how to not just execute them, but also to collect result from them to some collection... Lets say I have a scheduled task that returns a random number every time:

val task = Task { Math.random() }
implicit val io: SchedulerService = Scheduler.io()
task.map(_ + 2).map(println).executeOn(io).delayExecution(1.seconds).loopForever.runAsyncAndForget

Theoretically speaking, I can create mutable and concurrent list before task execution, and in task.map I can put a result in that list... But I've heard that using mutable, shared between threads, collections isn't the best practice at all... Is there any nice way to collect all scheduled Task results? What instrument should I use to achieve this goal in a proper, scala idiomatic way, avoiding mutable collections?


Solution

  • The idiomatic way to collect repeated results using Monix would be to use an Observable instead of a Task. It has many methods such as zipMap to combine results with another Observable, and many methods such as foldLeft to combine results with previous results of the same Observable.

    Note this generally requires collecting all your Observables into one method instead of the fire and forget method in your example. Ideally, you have exactly one runAsync in your entire program, in your main function.