Home » Android » android – Kotlin observeForever every time is null-Exceptionshub

android – Kotlin observeForever every time is null-Exceptionshub

Posted by: admin February 26, 2020 Leave a comment

Questions:

i’m trying realise some global object for my app and observe inside to some LiveData from my DAO. Here is how it looks:

object appCommon {
    @Volatile
    lateinit var config: Config

    suspend fun initAppCommon() {
        GlobalScope.launch(Dispatchers.Main) {
            Database_mW.getDBInstance(AppController.appInstance).ConfigDAO().getLive()
                .observeForever(Observer {
                    config = it
                })
        }

        initConfig()
    }

    private suspend fun initConfig() {
        withContext(Dispatchers.IO) {
            if (Database_mW.getDBInstance(AppController.appInstance).ConfigDAO().get() == null) {
                Database_mW.getDBInstance(AppController.appInstance).ConfigDAO().insert(Config(getDeviceSerialNumber(), "", "", ""))
            }
        }
    }
}

Here is DAO:

@Dao
interface Config_dao {

    @Insert(onConflict = OnConflictStrategy.IGNORE)
    fun insert(config: Config)

    @Update
    fun update(config: Config)

    @Query("DELETE FROM Config")
    fun clear()

    @Query("SELECT * from Config LIMIT 1")
    fun get(): Config

    @Query("SELECT * from Config LIMIT 1")
    fun getLive(): LiveData<Config>

    @Query("update Config set device_secret = :secret")
    fun updateSecret(secret: String)
}

So when i’m calling ConfigDAO().insert, observer is invoking but it = null.
Can somebody explain how to get latest inserted object inside observer for to update my global var?

How to&Answers: