Observing LiveData from ViewModel

后端 未结 6 2038
-上瘾入骨i
-上瘾入骨i 2021-01-30 05:07

I have a separate class in which I handle data fetching (specifically Firebase) and I usually return LiveData objects from it and update them asynchronously. Now I want to have

6条回答
  •  感情败类
    2021-01-30 05:20

    Use Kotlin coroutines with Architecture components.

    You can use the liveData builder function to call a suspend function, serving the result as a LiveData object.

    val user: LiveData = liveData {
        val data = database.loadUser() // loadUser is a suspend function.
        emit(data)
    }
    

    You can also emit multiple values from the block. Each emit() call suspends the execution of the block until the LiveData value is set on the main thread.

    val user: LiveData = liveData {
        emit(Result.loading())
        try {
            emit(Result.success(fetchUser()))
        } catch(ioException: Exception) {
            emit(Result.error(ioException))
        }
    }
    

    In your gradle config, use androidx.lifecycle:lifecycle-livedata-ktx:2.2.0 or higher.

    There is also an article about it.

    Update: Also it's possible to change LiveData in the Dao interface. You need to add the suspend keyword to the function:

    @Query("SELECT * FROM the_table")
    suspend fun getAll(): List
    

    and in the ViewModel you need to get it asynchronously like that:

    viewModelScope.launch(Dispatchers.IO) {
        allData = dao.getAll()
        // It's also possible to sync other data here
    }
    

提交回复
热议问题