3

I have a ConstraintsResolver class which resolves a queue of Constraints. This is done when a ConstraintsResolver object calls meetConstraint() on a Constraint one.

Most of meetConstraint() implementations will return immediately, so I could just return a boolean, but there is at least one that will block, which means I need to implement the callback pattern.

Do I have an option to combine both solutions or I have to implement only the callback pattern?

Themelis
  • 139

2 Answers2

4

It looks like you have a code with both synchronous and asynchronous nature. If you need to combine it in a clean/organized way, you can use reactive programming paradigm. Check out the Observable pattern.

You might also achieve your goals with simpler tools like promises. (In Java standard library, they are called Future and there’s also a related CompletableFuture framework).

1

It seems to me you don't need the callback pattern here. You just need threads.

Sync answers seem mandatory, since you will continue the process after receiving the response.

But I fail to see what would an async answer would improve. Anyway, you will be waiting for a response. Anyway, you are blocked. If such blocking stops other tasks, just use threads.

Callbacks are not used to unblock processes (for that, synchronous answers are just enough). They are just used when an interactor could send data by surprise. For example, I give a task to an employee and I give him my phone number, so he can "call me back" if something bad happens. If not, I don't need to know it.

If I am waiting for his call to continue my process, that's not a "back call", but just the synchronous answer I was waiting for.

RodolfoAP
  • 256