https://kotlinlang.org logo
Title
a

Antanas A.

02/21/2019, 9:11 AM
Hi, Is it possible to make suspend function calls to tail recursive when nested function calls outer function? Now in the example I'm getting stackoverflow. Do anyone have a suggestions what the proper way to implement this logic?
suspend fun connectToSocket() {
            suspend fun process(session: DefaultClientWebSocketSession) {
                while (session.isActive) {
                    session.incoming.onReceiveOrNull { frame ->
                        if (frame == null) {
                            session.close()
                            delay(2000)
                            connectToSocket() // <- do reconnect
                        }
                    }
                }
            }
            process(startSession())
        }
        connectToSocket()
s

spand

02/21/2019, 9:39 AM
Move the loop out ie:
suspend fun connectToSocket() {
	suspend fun process(session: DefaultClientWebSocketSession) {
		while (session.isActive) {
			session.incoming.onReceiveOrNull { frame ->
				if (frame == null) {
					session.close()
				}
			}
		}
	}
	process(startSession())
}
        
while (true){
	connectToSocket()
	delay(2000)
}
a

Antanas A.

02/21/2019, 10:01 AM
yes, probably that way, just need to manage out how to return status from connectToSocket() because onReceiveOrNull doesn't allow return from prcess function, and websocket.wss(url) { process(this) } wss itself returns Unit
s

spand

02/21/2019, 10:04 AM
If the
process
function is a problem why dont you just remove/inline it ?
a

Antanas A.

02/21/2019, 10:06 AM
it's only because of ws and wss
when (uri.protocol.isSecure()) {
                true -> client.wss(host = uri.host, port = uri.port, path = uri.encodedPath) { process(this) }
                false -> <http://client.ws|client.ws>(host = uri.host, port = uri.port, path = uri.encodedPath) { process(this) }
            }
so I've extracted logic into process