Hi, Any ideas on how to make this work? I need to ...
# dagger
s
Hi, Any ideas on how to make this work? I need to observe the API URL change from shared preferences in the APIModule but Hilt doesn't like the idea of injecting constructor here... Modules that need to be instantiated by Hilt must have a visible, empty constructor.
Copy code
@Module
@InstallIn(SingletonComponent::class)
class ApiModule @Inject constructor(
    localPrefs: SharedPreferences,
    app: Application,
) {

    init {
        localPrefs.registerOnSharedPreferenceChangeListener { prefs: SharedPreferences?, key: String? ->
            if (key == app.getString(R.string.pref_key_api_url)) {
                val newApiUrl = prefs?.getString(key, defaultApiUrl) ?: defaultApiUrl
                Logger.w("API URL CHANGED!!! $newApiUrl")
            }
        }
    }
}
s
Would field injection work (instead of constructor injection)?
s
It didn't work either. lateinit var localPrefs is not initialized.
s
They won't be initialized at the time that
init { .... }
is called; they'll be initialized a bit later. You may need to create a (lazy) accessor or create a method you'd need to call explicitly to do what happens originally in your
init
block...
s
yes I need to do some experiments
Better sleep over the problem for now... 😴