Skip to content

Snappy1

  • Home
  • Android
  • What
  • How
  • Is
  • Can
  • Does
  • Do
  • Why
  • Are
  • Who
  • Toggle search form

[FIXED] android – lateinit var for LiveData

Posted on November 11, 2022 By

Solution 1 :

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.

Solution 2 :

The simplest option seems like MutableLiveData:

class MainViewModel {
    private val _timeStamps = MutableLiveData<List<TimeStamp>>()
    val timeStamps: LiveData<List<TimeStamp>> = _timeStamps

    init {
        viewModelScope.launch {
            // inspect the data and set a value on _timeStamps
        }

Depending on what the coroutine is doing, there may be other options (e.g., asLiveData() on a Flow, MediatorLiveData).

Problem :

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.

READ  [FIXED] android - Syn data when internet is available
Powered by Inline Related Posts

How can I improve this code?

Comments

Comment posted by cactustictacs

You shouldn’t need to do this anyway – a

Comment posted by user1785730

emit()

Comment posted by Sergio

@user1785730 please check my updated answer. You can call

Comment posted by user1785730

When I set up

Comment posted by CommonsWare

@user1785730: I do not know what database you are referring to. But, if you call

Comment posted by user1785730

That is not what I want to do. After the initial logic to figure out the data I want

Comment posted by user1785730

There are two cases: in both cases I assign to

Comment posted by CommonsWare

@user1785730: You could use

Android Tags:android, android-livedata, kotlin, kotlin-coroutines, race-condition

Post navigation

Previous Post: [FIXED] android developer api – there is a ‘Late Initialization Error’ during flutter development
Next Post: [FIXED] android – How to set SSL pinning using retrofit for Firebase Realtime Database Url?

Related Posts

[FIXED] kotlin – Android: How can I use send data from Room to Retrofit without LiveData? Android
[FIXED] android – Is there any misunderstanding about the onActivityCreated fragment callback? Android
[FIXED] android – How can I implement RefreshIndicator in Listview.Builder using Getx? Android
[FIXED] Getting error ‘Attempt to invoke virtual method ‘void android.widget.TextView.setText(java.lang.CharSequence)’ ON andoid app Android
[FIXED] Android Slow Bluetooth RFCOMM Transfer Rate with RN4678 Android
[FIXED] java – Can we play our YouTube channel videos in our app? Android

Archives

  • March 2023
  • February 2023
  • January 2023
  • December 2022
  • November 2022
  • October 2022
  • September 2022

Categories

  • ¿Cómo
  • ¿Cuál
  • ¿Cuándo
  • ¿Cuántas
  • ¿Cuánto
  • ¿Qué
  • Android
  • Are
  • At
  • C'est
  • Can
  • Comment
  • Did
  • Do
  • Does
  • Est-ce
  • Est-il
  • For
  • Has
  • Hat
  • How
  • In
  • Is
  • Ist
  • Kann
  • Où
  • Pourquoi
  • Quand
  • Quel
  • Quelle
  • Quelles
  • Quels
  • Qui
  • Should
  • Sind
  • Sollte
  • Uncategorized
  • Wann
  • Warum
  • Was
  • Welche
  • Welchen
  • Welcher
  • Welches
  • Were
  • What
  • What's
  • When
  • Where
  • Which
  • Who
  • Who's
  • Why
  • Wie
  • Will
  • Wird
  • Wo
  • Woher
  • you can create a selvedge edge: You can make the edges of garter stitch more smooth by slipping the first stitch of every row.2022-02-04
  • you really only need to know two patterns: garter stitch

Recent Posts

  • What are the main features of Islamic education?
  • Is the Jeep 4xe worth it?
  • How does the ringer work on cast iron?
  • What is the biggest size interior door?
  • Is blue raspberry an original Jolly Rancher flavor?

Recent Comments

No comments to show.

Copyright © 2023 Snappy1.

Powered by PressBook Grid Dark theme