I’m new to Kotlin, though very proficient in C++17. Kotlin coroutines seem very appealing to me to implement networking protocols. However, I could use some help in understanding coroutines for my use case.
Let’s look at an HTTP client for example. Typically, handling the initial headers requires some sort of per-connection state machine. First state when the client receives the response: Client is receiving the HTTP response line. Next state: Client is receiving the HTTP response headers. This state continues until an empty line is received etc.
Typically, I’d implement this as a set of states and
when statements. As soon as I’m done parsing incoming data, I take a state dependent action. If for example I received the newline character of the HTTP response line, I can parse said response line and switch to the next state etc.
However, with coroutines, I can implement this entire sequence in one suspending function. Any time I run out of data, I could suspend the function somehow until I get more data.
The question is how to suspend the function. I need to suspend whenever more data is needed. In addition, it would be useful to communicate to the outside world what custom HTTP headers were received to give outside code the chance to evaluate them and decide whether or not they are valid.
In classical code, I’d use callbacks for fetching more data and for letting user code validate custom HTTP headers. In here, I’d like to somehow inform the outside world that I need more data or have HTTP headers to validate, and suspend the function until that operation was performed.
What would the proper approach be? I could fiddle around with continuations manually, though I guess this is discouraged until I really need to touch continuations manually. So, what else? A Sequence perhaps? Or channels? The latter work with only one data type though, right?