Refactoring the code to handle lifecycles better