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


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 {
    lateinit var config: Config

    suspend fun initAppCommon() {
        GlobalScope.launch(Dispatchers.Main) {
                .observeForever(Observer {
                    config = it


    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:

interface Config_dao {

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

    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: