Value not saved into the data class

331 Views Asked by At

I am currently building an app and I have added Dagger Hilt in order to define a single class to access data. the injection seems working fine but I am not able to store a value in the data class I use.

I have created a Singleton first, which is used by the code to set/get value from a data structure.

@Singleton
class CarListMemorySource @Inject constructor() : CarListInterface {

    private var extendedCarList: ExtendedCarList? = null

    override fun setListOfVehicles(listOfVehicles: List<item>) 
    {
        extendedCarList?.listOfVehicles = listOfVehicles
    }

}

When I am calling setListOfVehicles the listOfVehicules contains 10 items but

The data structure ExtendedCarList is defined as below:

data class ExtendedCarList(
    var listOfVehicles: List<item>
)

The Singleton in passed using Hilt like for example in the viewModel below:

@HiltViewModel
class HomeScreenViewModel @Inject constructor(
    private val carList: CarListMemorySource
): ViewModel() {

    fun getList() {
        --> DO SOMETHING TO Get A ListA
        carList.setListOfVehicles(ListA)
    }
}

And in the activity, using the viewModel, I am just doing this:

@AndroidEntryPoint
class HomeScreenActivity: AppCompatActivity() {

   private val viewModel: HomeScreenViewModel by viewModels()

....
    viewModel.getList()
....

}

Any idea why and how to fix it ?

Thanks

1

There are 1 best solutions below

0
On

you never initialize extendedCarList.

extendedCarList?.listOfVehicles = listOfVehicles

above line is exactly the same as

if (extendedCarList != null) extendedCarList.listOfVehicles = listOfVehicles

But it never passes the null check.

I think just changing

private var extendedCarList: ExtendedCarList? = null

to

private val extendedCarList = ExtendedCarList()

might solve it