koin icon indicating copy to clipboard operation
koin copied to clipboard

Dependency is null when trying to access it on abstract class property initialisation

Open mgoyanes opened this issue 5 years ago • 3 comments

Filling this as a bug but don't know if it is a bug.

My ProductsViewModel implements the abstract class AbstractProductsViewModel. I'm passing some dependencies to the ProductsViewModel and when the AbstractProductsViewModel is being created, one of its properties triggers a method in ProductsViewModel.

open val product: LiveData<Product> =  { 
        // gets the product from the database and calls method in ProductsViewModel
        generateProduct(product)
    }

I'm getting the error:

 Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'androidx.lifecycle.LiveData com.XXX.repository.ProductsRepository.getProductNumber()' on a null object reference
        at com.XXX.ProductsViewModel.generateProduct(ProductsViewModel.kt:82)
        at com.XXX.AbstractProductsViewModel.<init>(AbstractProductsViewModel.kt:54)
        at com.XXX.ProductsViewModel.<init>(ProductsViewModel.kt:35)

ProductsRepository is being passed in the constructor and while I'm debugging I can see that it is not null but when I try to access it is null. I put a breakpoint just before trying to access the ProductsRepository in the generateProduct product method and in there, it is null but if I go up in the debugger "frames" I can see it is not null.

image

Any idea why and How can I overcome this?

mgoyanes avatar Mar 01 '21 09:03 mgoyanes

Have you found any solution for this issue?

n1n3b1t avatar Oct 13 '21 09:10 n1n3b1t

This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions.

stale[bot] avatar Apr 11 '22 10:04 stale[bot]

I did face the very same issue

androks avatar Oct 22 '24 17:10 androks