President Obama used his farewell speech here on Tuesday to outline the gathering threats to American democracy and press a more optimistic vision for a country that seems more politically divided than ever.

Obama said goodbye to the nation against the backdrop of one of the most corrosive elections in U.S. history and a deep sense that the poisonous political environment has pitted Americans against each other.

“America, we weaken those ties when we allow our political dialogue to become so corrosive that people of good character aren’t even willing to enter public service; so coarse with rancor that Americans with whom we disagree are not just misguided, but malevolent,” Obama said. “We weaken those ties when we define some of us as more American than others; when we write off the whole system as inevitably corrupt, and blame the leaders we elect without examining our own role in electing them.”

Obama fretted about anti-immigrant sentiment, racism and economic inequality.

“If every economic issue is framed as a struggle between a hard-working white middle class and an undeserving minority, then workers of all shades will be left fighting for scraps while the wealthy withdraw further into their private enclaves,” Obama warned in an not-so-subtle jab at his successor, President-elect Donald Trump.

(Victoria Walker/The Washington Post)

Obama, the first African American president, acknowledged the continuing difficulty of race relations in America.

“After my election, there was talk of a post-racial America. Such a vision, however well-intended, was never realistic,” he said. “For race remains a potent and often divisive force in our society. Now, I’ve lived long enough to know that race relations are better than they were 10, or 20, or 30 years ago — you can see it not just in statistics, but in the attitudes of young Americans across the political spectrum. But we’re not where we need to be.”

He took note of overseas threats including “violent fanatics who claim to speak for Islam” and “autocrats in foreign capitals who see free markets, open democracies and civil society itself as a threat to their power.”

The president recalled his days as a community organizer in some of Chicago’s toughest neighborhoods. “This is where I learned that change only happens when ordinary people get involved, get engaged, and come together to demand it,” he said of his adopted home town.

While most recent presidential farewell addresses have been delivered from the quiet of the Oval Office, Obama spoke before a crowd of 20,000 at McCormick Place, the largest convention center in North America and the site of his 2012 campaign victory address.

In his victory speech, Obama promised a cheering crowd of supporters that “the best is yet to come.” On Tuesday the president, whose approval rating has surged even as his party’s fortunes have suffered, tried to lay out an optimistic vision to a deeply partisan crowd fearful of a Trump presidency.

“Yes, our progress has been uneven. The work of democracy has always been hard, contentious and sometimes bloody,” he said. “For every two steps forward, it often feels we take one step back. But the long sweep of America has been defined by forward motion, a constant widening of our founding creed to embrace all, and not just some.”

1 of 20 Full Screen Autoplay Close Skip Ad × Here’s what it looked like during President Obama’s farewell speech in Chicago View Photos The president delivered his farewell speech to the nation in his home town of Chicago. Caption The president addressed the nation in his home town of Chicago. Jan. 10, 2017 President Obama acknowledges the crowd as he arrives to deliver his farewell address at McCormick Place in Chicago. John Gress/Reuters Buy Photo Wait 1 second to continue.

But the last months of Obama’s presidency had tested his vision for the country in ways he probably never expected. First there was a violent summer of police shootings and protests that highlighted the country’s racial division.

A president who preached “Yes we can” on the campaign trail was asking a different question this summer after the killing of two men by police in Minnesota and Louisiana and by the murder of five police officers in Dallas. “Can we do this? Can we find the character as Americans to open our hearts to each other?” he asked. “I don’t know.”

Then there was the stunning victory of President-elect Trump, a candidate whom Obama derided as unfit for the Oval Office.

The emotional crowd roared and stamped its feet on the bleachers in approval when Obama took the stage, and chanted “four more years” when a heckler threatened to interrupt him. Obama, meanwhile, veered from professions of optimism about the country’s future to stark warnings about the threats to American democracy if citizens did not demand more from their politicians.

He spoke repeatedly of the need for empathy, saying that Americans of color needed to tie “our own struggles for justice to the challenges that a lot of people in this country face,” including “the middle-aged white guy . . . who’s seen his world upended by economic and cultural and technological change.”

He called on white Americans to acknowledge “that the effects of slavery and Jim Crow didn’t suddenly vanish in the ’60s.”

“We have to pay attention,” Obama implored the crowd, “and listen.”

The president was speaking to multiple audiences in Chicago. He sought to unite a country that has grown more cynical and divided over the course of his presidency by reminding Americans of all that they have in common.

He worked to rally his supporters, who failed to back Hillary Clinton, his chosen successor, in sufficient numbers. And he sought to make a case for historians that the last eight years had produced lasting, positive change that would not be undone by his successor.

To that end, Obama’s speech focused, in part, on recounting and celebrating his accomplishments for a crowd in the auditorium that included many of his most loyal staffers who had journeyed to Chicago.

The pageantry surrounding Tuesday’s speech — which presidential historian Douglas Brinkley described as “the most highly publicized farewell address in American history” — bore all the hallmarks of a White House that has meticulously cultivated the president’s image in the digital age. Hours before he arrived, television screens showed footage of comic outtakes from White House videos as well as stunning images from his visits to Stonehenge, Rome’s Colosseum and other sites. At other points, curated tweets from the event flickered across the screens.

The big crowd, full of White House staffers, celebrities and longtime supporters, made the event feel like a cross between a campaign rally and a wake.

In touting his legacy on Tuesday, Obama spoke of bringing home the vast majority of the troops deployed to Iraq and Afghanistan, forging an international agreement to curb Iran’s nuclear program and rallying the world around a major climate change accord.

Domestically, he highlighted the more than 20 million people who are now insured because of the Affordable Care Act, an economy that has generated 75 months of consecutive job growth and incomes that are finally rising after years of stagnation. He celebrated social and cultural changes, such as the expansion of same-sex marriage to all 50 states.

Trump’s victory has put some of that legacy — particularly Obama’s signature health-care law and global climate change pact — in doubt.

Obama’s references to expanded health-care coverage, the legalization of same-sex marriage and tolerance for immigrants and minorities drew the loudest applause and cheers. But when he mentioned the prospect of Trump’s inaugural — “In 10 days, the world will witness a hallmark of our democracy” — a murmur of boos rippled through the audience.

Even as he touted his accomplishments and rallied his supporters, Obama pointed to the places where he said U.S. politics was failing.

“But without some common baseline of facts; without a willingness to admit new information . . . then we’re going to keep talking past each other,” he said. “And isn’t that part of what so often makes politics dispiriting?”

He warned that denying climate change not only “betrays future generations, it betrays the essential spirit of this country.”

He called on Americans to be “anxious, jealous guardians of our democracy” and to break out of their ideological bubbles.

“If you’re tired of arguing with strangers on the Internet, try talking with one of them in real life,” he said to cheers, before urging people to run for office. “Show up. Dive in. Stay at it.”

The unanswerable question was how long Obama’s call to action will last beyond his speech and the coming inauguration.

For Obama, the goal was to deliver a speech that was larger than any single policy that could be reversed or repealed, said Chicago Mayor Rahm Emanuel, who served as Obama’s first White House chief of staff and was in the audience Tuesday. This was a speech that was “not about specific policies, but a specific sense of who we are,” Emanuel said.

“Yes We Can,” the president said, invoking the catchphrase of his first presidential bid.

“Yes We Did,” he added, as audience members stamped their feet on the bleachers in time to his words. “Yes We Can.”

Jaffe reported from Washington.