Search code examples
androidkotlinretrofitrx-javareactivex

Kotlin: How to check variable with lateinit property is initialized or not


I have a variable that is declared like

private lateinit var apiDisposable: Disposable

and then in onPause() method, I am doing

override fun onPause() {
    super.onPause()
    if (!apiDisposable.isDisposed)
        apiDisposable.dispose()
}

But I get this

kotlin.UninitializedPropertyAccessException: lateinit property apiDisposable has not been initialized

Can anyone tell me how could I check if this variable is initialized or not? Is there any method like isInitialised()

Any help would be appreciated


Solution

  • Declare your property as a simple property of a nullable type:

    private var apiDisposable: Disposable? = null
    

    Call the method using the safe call notation:

    override fun onPause() {
        super.onPause()
        apiDisposable?.dispose()
    }
    

    lateinit is reserved for variables that are guaranteed to be initialized, if this is not your case - don't use it.