Joel
Joel

Reputation: 23140

In Corda, how to start a flow from a service?

I have created a CordaService running on my node. I want this service to start flows based on various conditions. However, the ServiceHub provided to the service does not provide the ability to start flows.

Is there any flow for a service to start a flow? How would I do thi?

Upvotes: 2

Views: 614

Answers (2)

Rodrigo
Rodrigo

Reputation: 372

Yes, pass AppServiceHub to the constructor

In Kotlin:

class MyCordaService(private val serviceHub: AppServiceHub) : SingletonSerializeAsToken() {

    init {
        // code ran at service creation / node startup
    }

    // public api of service
}

or Java:

public class MyCordaService extends SingletonSerializeAsToken {

    private AppServiceHub serviceHub;

    public MyCordaService(AppServiceHub serviceHub) {
        this.serviceHub = serviceHub;
        // code ran at service creation / node startup
    }

    // public api of service
}

Important: to avoid possible any potential deadlocks between running nodes, start inner flows from their own Thread

For example:

public class MyCordaService extends SingletonSerializeAsToken {

    private AppServiceHub serviceHub;

    public MyCordaService(AppServiceHub serviceHub) {
        this.serviceHub = serviceHub;
        // code ran at service creation / node startup
    }

    // public api of service
   public void doSomething(){   
    // do something and start a new flow
    Thread flowThread = new Thread(new StartFlow());
    flowThread.start();
   }

   private class StartFlow implements Runnable {
     @Override
        public void run() {
         // start new flow
         CordaFuture<SignedTransaction> cordaFuture=  appServiceHub.startFlow(new 
         Flow(params).getReturnValue();

         SignedTransaction signedTransaction = cordaFuture.get();
        }
   }
}

Upvotes: 1

Joel
Joel

Reputation: 23140

Yes. Simply pass your CordaService an AppServiceHub instead of a ServiceHub in its constructor.

The AppServiceHub interface extends the ServiceHub interface to give a node the ability to start flows:

interface AppServiceHub : ServiceHub {

    fun <T> startFlow(flow: FlowLogic<T>): FlowHandle<T>

    fun <T> startTrackedFlow(flow: FlowLogic<T>): FlowProgressHandle<T>
}

Upvotes: 1

Related Questions