Is there an easy way to update an already initialized class based on an asynchronous event?
Scenario - I have an object that lives within my program. However, the attributes on this object periodically become out of sync with my database. This is because when the data changes, the asynchronous code updates the database. How can I let my object know that it needs to adapt? Right now, I poll the database and update the object, but I copy/paste this logic all over in my code when it is critical that I have the up to date data. I would like to register the object with some kind of Event Handler so it is updated in memory whenever these changes occur.
pseudo code example of the problem -
class StaticObject:
def __init__(self, x):
self.attribute = x
async def await_api_update()
await new_attr = api.update()
database.update(new_attr)
# how could i update self.attribute = new_attr here?
def main():
static_obj = StaticObject()
function1(static_object)
# assume that await_api_update() has been called here
function2(static_object) # static_object would now have the new_attr without me polling the database
edit - Its also worth mentioning that I have many of these objects (the api spits out updates for multiple primary keys if you will) but the database updates are all handled through the same (one) asynchronous method, so I don't think its as easy as coupling the update() method with the object itself.