Forwarding and effects

This page documents how to use Cloudstate CRDT effects and forwarding in Java. For high level information on what Cloudstate effects and forwarding is, please read the general Forwarding and effects documentation first.

Looking up service call references

To forward a command or emit an effect, a reference to the service call that will be invoked needs to be looked up. This can be done using the ServiceCallFactory interface, which is accessible on any context object via the serviceCallFactory() method.

For example, if a user function serves two entity types, a shopping cart, and a CRDT that tracks which items are currently in hot demand, it might want to invoke the ItemAddedToCart command on example.shoppingcart.HotItems as a side effect of the AddItem shopping cart command. This reference can be looked up like so:

private final ServiceCallRef<Hotitems.Item> itemAddedToCartRef;

public ShoppingCartEntity(Context ctx) {
  itemAddedToCartRef =
      ctx.serviceCallFactory()
          .lookup(
              "example.shoppingcart.ShoppingCartService", "ItemAddedToCart", Hotitems.Item.class);
}

This could be looked up in the constructor of the entity, for later use, so it doesn’t have to be looked up each time it’s needed.

Forwarding command

To forward a command, ClientActionContext.forward() may be invoked. The CommandContext for each entity type implements ClientActionContext and so offers this function. If the hot items effect service call above were to be invoked as a forward, it would might look like this:

@CommandHandler
public void addItem(Shoppingcart.AddLineItem item, CommandContext ctx) {
  // ... Validate and emit event

  ctx.forward(
      itemAddedToCartRef.createCall(
          Hotitems.Item.newBuilder()
              .setProductId(item.getProductId())
              .setName(item.getName())
              .setQuantity(item.getQuantity())
              .build()));
}

Emitting an effect

To emit an effect, EffectContext.effect() may be invoked. The CommandContext for each entity type implements EffectContext and so offers this function. If the hot items effect service call above were to be invoked as an effect, it would might look like this:

@CommandHandler
public Empty addItem(Shoppingcart.AddLineItem item, CommandContext ctx) {
  // ... Validate and emit event

  ctx.effect(
      itemAddedToCartRef.createCall(
          Hotitems.Item.newBuilder()
              .setProductId(item.getProductId())
              .setName(item.getName())
              .setQuantity(item.getQuantity())
              .build()));

  return Empty.getDefaultInstance();
}
The source code for this page can be found here.