lateinit var for LiveData

Issue

In my ViewModel I have a lateinit var to hold some LiveData. The way this variable is initialized depends on the data and the current date. Can’t do it in SQL. This is the ViewModel:

class MainViewModel {
    lateinit var timeStamps: LiveData<List<TimeStamp>>

    init {
        viewModelScope.launch {
            val db = RoomDB.getInstance(application).timeStampDao()
            val lastTimeStamp = db.getLast()
            if (lastTimeStamp == null
                || (lastTimeStamp.instant < setToStartOfDay(Calendar.getInstance()).timeInMillis)
                && lastTimeStamp.action == ACTION.END_WORK) {
                timeStamps = db.getAllAfterLive(Calendar.getInstance().timeInMillis)
            } else {
                db.getLastAction(ACTION.START_WORK)?.let { lastStartWork ->
                    val startOfDay = setToStartOfDay(initCalendar(lastStartWork.instant)).timeInMillis
                    db.getFirstActionAfter(ACTION.START_WORK, startOfDay)?.let {
                        timeStamps = db.getAllAfterLive(it.instant)
                    }
                }
            }

Here I access timeStamps in my Activity:

override fun onCreate(savedInstanceState: Bundle?) {

    viewModel.timeStamps.observe(this) { list -> recordsAdapter.submitList(list) }

This leads to a UninitializedPropertyAccessException: onCreate runs faster than the timeStamps initialization launched in parallel.

I fixed this by introducing another lateinit var for a callback:

class MainViewModel {
    lateinit var timeStamps: LiveData<List<TimeStamp>>
    lateinit var timeStampsInitializedCallback: () -> Unit

    init {
        viewModelScope.launch {
            // inspect the data and initialize timeStamps
            timeStampsInitializedCallback()
        }

which I initialize in onCreate:

override fun onCreate(savedInstanceState: Bundle?) {

    viewModel.timeStampsInitializedCallback = {
        viewModel.timeStamps.observe(this) { list -> recordsAdapter.submitList(list) }
    }

This works, but it introduces a race condition. Should the initialization for timeStamps unexpectedly finish before the callback is initialized, I’d get another UninitializedPropertyAccessException and be back where I started.

How can I improve this code?

Solution

You can also use liveData builder function:

class MainViewModel {
    val timeStamps: LiveData<List<TimeStamp>> = liveData {
        // inspect the data and initialize timeStamps
        emit(timeStamps) // emit list of TimeStamps
        emitSource(liveData) // emit another LiveData
    }

}

// in Activity

override fun onCreate(savedInstanceState: Bundle?) {
    viewModel.timeStamps.observe(this) { list -> recordsAdapter.submitList(list) }
}

The liveData code block starts executing when LiveData becomes active and is automatically canceled after a configurable timeout when the LiveData becomes inactive.

Answered By – BigSt

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published