I also go to the gym throughout the week but I usually am focusing on the workout too much to think about coding.
Sometimes I just have to more or less sleep on it though. I work on some other part of the project and come in the next day with fresh perspective. It's probably always kinda rolling around in the back of my head to some degree.
The Learning How to Learn course(free on Coursera) talks about focused mode vs diffused mode of thinking. I think you might find topic interesting. https://www.coursera.org/learn/learning-how-to-learn