guild icon
Toit
#Callback-like paradigm for http.Server
Thread channel in help
Tony
Tony 08/19/2024 08:35 PM
I am building off of the http.Server examples, but I cannot figure out the idiomatic way to handle something like a callback. I'd like to define a function like this:

start-server [--on-open] [--on-close] [--on-message]: ... server.listen server-socket :: | request/http.RequestIncoming writer/http.ResponseWriter | ...

But I cannot use the the passed in blocks (eg, --on-open) inside the lambda passed to server.listen.

What is the idiomatic way to do this in Toit?
Tony
Tony 08/19/2024 08:38 PM
Maybe define an interface and pass the object to start-server?
Tony
Tony 08/19/2024 08:48 PM
It's not what the functional part of me wants to write, but it does seem workable.
bitphlipphar
bitphlipphar 08/20/2024 06:25 AM
You can use a lambda instead of a block. The server.listen call takes two arguments, the last one is a lambda.
bitphlipphar
bitphlipphar 08/20/2024 06:25 AM
So change --on-open to take a lambda instead, perhaps?(edited)
bitphlipphar
bitphlipphar 08/20/2024 06:26 AM
start-server --on-open/Lambda --on-close/Lambda --on-message/Lambda:
Tony
Tony 08/20/2024 06:27 PM
Thank you for the suggestion. I might give that a try later, but I am OK with the version I ended up with: https://github.com/anthonyjclark/cs181r/blob/main/_toit/communication/communication.toit

I did not find documentation on creating lambdas, so I took that lack of documentation as a recommendation to find a different approach.
7 messages in total