Eugene
Eugene

Reputation: 1125

Can a service update a controller in Spring boot for long processes

this is a question more about communication between service and controller annotated classes in spring boot. I have a RestController class that exposes a POST mapping which calls a method in the Service class. Now this method may take a long time running; hence there is a need to send some kind of feedback to the controller.

Is there any mechanism which allows a service to call/update a method/variable in the controller?

Upvotes: 1

Views: 275

Answers (1)

Khaled Ahmed
Khaled Ahmed

Reputation: 1134

one of the most simplest ways is passing some lamda function from the controller to the service and call it from the service like this

Controller Class

@RestController
public class controller {
    @Autowired
    Service service;

    public void foo() {
            service.foo(..parms, (message/*any params you want*/) -> {
                // here the body that will receive the message from the service
                System.out.print(message);
            });
    }
}

Service Class

public class Service {
    // updateStatus here is the function you will send the update to the controller from
    public void foo(...params, updateStatus) {
        updateStatus("starting the process...");
        // do some code
        updateStatus("in progress...");
        // do some code
        updateStatus("completed");
    }
}

Upvotes: 3

Related Questions