Persisting list of events conditionally

Suppose you come up with a list of events to persist based on certain condition which then you have to persist at some later point in time.

var value = value1
var eventsToPersist = Nil

if condition1:
   value = value2
   eventsToPersist = Seq(UpdateLeaves, SomethingElse1)
if condition 2: 
   value = value3
   eventsToPersist = Seq(CancelLeaves, SomethingElse2)

if(compute(value)):
    ctx.thenPersistAll(eventsToPersist, EmployeeRelease)
else 
    ctx.thenPersist(EmployeeRelease)

ctx.thenPersistAll doesn’t seem to accept a list of events instead it expects Events. How am I suppose to achieve refactoring such a use case? All I do is end up repeating myself. Please help.

I think the snippet speak for itself. Let me know if I need to elaborate more. But basically, I believe the framework should allow me to collect events as a list before persisting them all together.

Just worked through this myself. Unpack the list of events with the :_* operator:

if(compute(value)):
    ctx.thenPersistAll(eventsToPersist :_* , EmployeeRelease)
1 Like

I got following error when I tried your solution to fit my usecase:

no `: _*' annotation allowed here
[error] (such annotations are only allowed in arguments to *-parameters)
[error]               eventsToPersist :_*,
[error]                               ^

however, then I improvised on it to make it work like so:

eventsToPersist ++
  List(LastLeavesSaved(newState.id, balanced.earned, balanced.currentYearEarned, balanced.sick, balanced.extra),
       LeavesCredited(newState.id, balanced.earned, balanced.currentYearEarned, balanced.sick, balanced.extra),
       EmployeeUpdated(newState.id, newState.name, newState.gender, newState.doj, newState.dor, newState.designation, newState.pfn, newState.contactInfo, newState.location, newLeaves, newState.roles),
       EmployeeReleased(newState.id, today)): _*

Much thanks @PkPwc