Callback Pinned to Service

../../_images/example-callback-pin.png

Callback pinned to service

Source Code for the Example

ListenerApi.java

Create the class ListenerApi.java:

package example;

public interface ListenerApi
{
  void onEvent(String data);
}

MyServiceImpl.java

Create the class MyServiceImpl.java:

package example;

import javax.inject.Inject;
import io.baratine.core.Lookup;
import io.baratine.core.Modify;
import io.baratine.core.Result;
import io.baratine.core.Service;
import io.baratine.store.Store;
import java.util.*;

@Service("public:///my-service")
@Startup
public class MyServiceImpl extends MyService
{
  private ExternalManager _extManager;
  private ListenerApi _callback;

  @OnInit
  private void onInit()
  {
    ServiceRef self = ServiceRef.current();

    _extManager = ExternalManager.create();

    ListenerApi listenerImpl = v->onEvent(v);

    _callback = self.pin(listenerImpl)
                    .as(ListenerApi.class);

    manager.register(_callback);
  }

  private void onEvent(String value)
  {
    ServiceRef self = ServiceRef.current();

    System.out.println("Event: " + value + " in " + self);
  }

  @OnDestroy
  private void onDestroy()
  {
    _extManager.unregister(_callback);
  }
}