rsoesemann / apex-chainable

Chain Asynchronous Apex in a readable and flexible way without hardcoding the successor.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Apex Chainable Codacy Badge

Deploy to Salesforce

Apex Batches can be chained by calling the successor batch from the finish() method of the previous batch. But such hardcoding makes this model inflexible. It's hard to build the chain from outside, neighter from a central class nor on runtime dependant on business logic.

The same applies when the execute() method of Schedulable or Queueable classes call other classes.

With Chainable

The Chainable wrapper class of this repository overcomes those drawbacks.

  • No need to hardcode successor batch in finish() method
  • Created batch chains of arbitrary length without changing existing Batch classes
  • Support Batchable, Queueable and Schedulable classes as chain members
  • Allows sharing and passing of variables between chain members
      new FirstBatch().setShared('result', new Money(0))
            .then(AnotherBatch())
            .then(QueueableJob())
            .then(ScheduledJob())
            ...
            .execute();

Without Chainable

class FirstBatch implements Batchable<SObject> {
    Iterator<SObject> start(BatchableContext ctx) { ... }

    void execute(BatchableContext ctx, List<Account> scope) { ... }

    void finish(BatchableContext ctx) {
        Database.enqueueBatch(new SecondBatch()); 
    }
}
class AnotherBatch implements Batchable<SObject> {
    Iterator<SObject> start(BatchableContext ctx) { ... }

    void execute(BatchableContext ctx, List<Account> scope) { ... }

    void finish(BatchableContext ctx) {
        System.schedule('name', cron, new ScheduledJob()); 
    }
}

About

Chain Asynchronous Apex in a readable and flexible way without hardcoding the successor.

License:MIT License


Languages

Language:Apex 89.2%Language:Shell 10.8%