Creating singletons using Initializer<T> vs object

Viewed 39

Heyo, I'm looking for some advice. I was taking some time to redo a chunk of my code to support dependency injection, and I found the androix.startup App Startup library. It seemed like a great solution for singleton registration, as dependencies and initialization order are automatically managed.

But, looking at the sample code, where they construct an ExampleLogger with a dependency on WorkManager...

// Initializes ExampleLogger.
class ExampleLoggerInitializer : Initializer<ExampleLogger> {
    override fun create(context: Context): ExampleLogger {
        // WorkManager.getInstance() is non-null only after
        // WorkManager is initialized.
        return ExampleLogger(WorkManager.getInstance(context))
    }

    override fun dependencies(): List<Class<out Initializer<*>>> {
        // Defines a dependency on WorkManagerInitializer so it can be
        // initialized after WorkManager is initialized.
        return listOf(WorkManagerInitializer::class.java)
    }
}

I'm left with a few questions. This code seems to construct a class object. How is this supposed to work if my singletons are already objects since object classes don't allow for constructors?

Assuming that ExampleLogger was an object, how should the create function look?

object ExampleLogger {
     lateinit var someProperty : String
     fun initialize(wm : WorkManager) {
         // do something
         // someProperty = wm.GetSomeProperty()
     }
}

class ExampleLoggerInitializer : Initializer<ExampleLogger> {
    override fun create(context: Context): ExampleLogger {
        ExampleLogger.initialize(WorkManager.getInstance(context))
        return ExampleLogger
    }

I guess my question is :

Is it okay that the create function doesn't return a new object, rather just an initialized object? I guess I'm worried that with an object, there's nothing guaranteeing that the initialization happened properly, and code can essentially access an uninitialized object.

Is there a better way to handle this?

0 Answers
Related