Is it necessary to specialize on a topic when writing publications?
No, it's by no means necessary to specialise on one topic for all your papers, and many people don't.

You do make it harder for yourself when you don't, though. Going into a new topic requires familiarity with a new area of cutting-edge research, learning which publication(s) to target, and maybe learning new methods.

And one of things I find most time-consuming is that you have to collect a new set of references. Once you've published within one topic, it's like you've laid down foundations in your literature review that you can build on again and again. But when you move to a new topic, you have to lay down new foundations: instead of simply updating your last literature review, you have to start rebuilding the foundations from a much smaller base. So you do find the really prolific people, who churn out maybe a dozen papers a year or more, have often stuck to a very narrow topic, and can get closer to staying on top of all the relevant literature.