There's a pattern I've tried a few times and never get it to work. It comes up a lot for me, and the solutions seems obvious , but I always run into issues.
The basic deal is something like a state machine that you use to get through the states required to connect to something, get various bits of required data, do handshaking exchanges, until you get to a ready state, handle loss of connection and cleanup. Pretty obvious stuff. It's in a loop since that connection can be gotten and lost over time.
It seems blindingly obvious that a sum type state enum would be the way to do this, with each step holding the data gotten up to that point. It means you don't have to have any mutable temps to