Most things in space move very predictably. For reasonably dense objects, like stars, planets or asteroids, gravity far outweighs all of the other forces acting on them, and it's not too hard to take account of gravity and predict their movements (if you have a powerful enough computer. For things like clouds of very thin gas it's a bit harder. So from the positions and movements of all the distant objects that we can see (at the time when the light we see them by left them), we can pretty accurately predict their movements a considerable way into the future, for instance up to possible collisions a few centuries out (for an asteroid) or a few billion years out (for Andromeda).
Of course there is a possibility of something unexpected happening -- between the light we see now being emitted and a possible future collision, a supermassive black hole travelling at close to the speed of light could pass through the Andromeda galaxy and scatter it, for instance, but we don't see things like that happening anywhere else in the universe, so it seems pretty unlikely to happen here.