Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Suggestion to add isInit() api to dagger.Lazy #4370

Open
xncHung opened this issue Jul 26, 2024 · 1 comment
Open

Suggestion to add isInit() api to dagger.Lazy #4370

xncHung opened this issue Jul 26, 2024 · 1 comment

Comments

@xncHung
Copy link

xncHung commented Jul 26, 2024

In my sample application, I collect closeable lazy objects (such as database connections) through a set, and then close these objects at the right time. However, I cannot determine whether the lazy object has been initialized. If a closeable object has not been accessed anywhere, it should be uninitialized. This object should be skipped when traversing the collection and closing it. However, I cannot determine whether the lazy object has been initialized. If I access the closeable object at this time, the object may be initialized when it is created, and then closed immediately. This behavior is meaningless and may be a time-consuming operation. Therefore, if lazy has an API to determine whether it has been initialized, this problem can be solved.

@HiltAndroidApp
class App : MultiDexApplication() {
    companion object {
        private const val TAG = "App"
    }

    @Inject
    @JvmSuppressWildcards
    internal lateinit var closeables: Set<Lazy<Closeable>>
    override fun onTerminate() {
        closeables.forEach {
            if (it.isInit()) {
                it.get().close()
            }
        }
        super.onTerminate()
    }
}

interface DbConnect : Closeable {

}

class DbConnectImpl @Inject constructor() : DbConnect {
    override fun close() {
//        close the db connect
    }

}

@Module
@InstallIn(SingletonComponent::class)
abstract class DbModule {
    @Binds
    @Singleton
    abstract fun bindDbConnect(impl: DbConnectImpl): DbConnect

}

@Module
@InstallIn(SingletonComponent::class)
object CloseModule {
    @Suppress("UNCHECKED_CAST")
    @Provides
    @IntoSet
    fun provideClosableWithDb(dbConnect: Lazy<DbConnect>): Lazy<Closeable> {
        return dbConnect as Lazy<Closeable>
    }
}
@bcorso
Copy link

bcorso commented Aug 5, 2024

@Chang-Eric and I discussed this briefly. It seems reasonable.

I think #2353 would likely also solve your issue since you are using Kotlin. Fwiw, you can probably use the same workarounds suggested in #2353 to convert to kotlin.Lazy.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants