"On June 30 I will leave the club, it's a decision I have taken with the president, with the staff," Xavi told reporters.
Champions Barcelona, third in the top flight, are 10 points behind leaders Real Madrid with their title defence virtually over.
"The feeling of being Barca coach is cruel, unpleasant, it feels like people lack respect for you a lot of the time," said Xavi.
"It's terrible on a mental health level, your morale ... to the point where you think there is no sense in continuing."
After elimination in the Copa del Rey by Athletic Bilbao this week and a thrashing by Madrid in the Spanish Super Cup final earlier in January, Xavi said he made the decision for the good of the club.
"I've thought about the club ... and above all the players," said Xavi.
"I have the feeling that I am doing the right thing, that I am acting with common sense.
"I think the club needs a change of dynamics, the dynamic is very negative."
Xavi, who took over in November 2021, led Barcelona to the Spanish Super Cup and league title last season, with the team built around a strong defence.
However this year they are fragile at the back and Saturday saw Barcelona let in five goals in La Liga at home for the first time since 1963.
Xavi said even if Barcelona won the Champions League he would not change his mind and stay.
The coach, 44, still thinks his team can win trophies this season.
"I am more optimistic than ever with this change of dynamic ... we'll go for La Liga, it's very difficult but we will fight," he added.
"I have not spoken to the players about it, I saw how down they were today and I will talk to them tomorrow, and that's one of the reasons for it."'Impossible' job
Xavi, who starred in midfield for Barcelona between 1998-2015, said his departure had been inevitable.
"It's happened to every coach that has been at this club, it's impossible that there's a (Alex) Ferguson of Barcelona," explained the coach, referring to the legendary Manchester United manager.
Xavi said if the team had beaten Villarreal he would not have announced he was stepping down on Saturday, but he had made the decision "some time ago".
"I was a solution two years and three months ago (when he was appointed), but now, thinking with my heart and about the club, for who I want the best, the best thing is for me to go on June 30," added Xavi.
"I have to thank the president (Joan Laporta) for his confidence, we have a great president."
Barcelona players spoke after the defeat by Villarreal before Xavi's decision, saying the team's collapse was not the coach's fault.
"There is full confidence in the technical team, it's the fault of the players," midfielder Frenkie de Jong told DAZN.
Defender Ronald Araujo said "of course" the team backed the coach.
"Since he came here, we've learnt a lot, we've been champions and it's almost the same team, plus a few more players," he explained.