简体   繁体   中英

How to use mutableLIveData in a function?

I am using MVVM pattern along with data-binding. My problem is that the data is not being updated even when the results are successful.

ViewModel Class is as below:

class HomeViewModel : ViewModel() {

var homeListener: HomeListener? = null
var overviewResponse: Overview?= null

fun convertStringToFloat(rating: String?): Float {
    var floatRating: Float = 0.0F
    if (rating != null) {
        floatRating = rating.toFloat()
    }

    return floatRating
}

 fun getDailyOverview() {
    Coroutines.main {
        val response = HoroscopeOverviewRepository().horoscopeOverview("Aries")
        if(response.isSuccessful){
            overviewResponse = response.body()
            Log.e("response", overviewResponse?.affirmation+"")
        }
    }

}}

I am calling getDailyOverview() from my fragment. How to observe the updated data?

I solved it by making the following changes to my viewmodel class:

class HomeViewModel : ViewModel() {

    var homeListener: HomeListener? = null
    var overviewResponse: Overview?= null

    private val _overview = MutableLiveData<Overview>()
    val overview: LiveData<Overview>
        get() = _overview

    init {
        _overview.value = overviewResponse
    }

    fun convertStringToFloat(rating: String?): Float {
        var floatRating: Float = 0.0F
        if (rating != null) {
            floatRating = rating.toFloat()
        }
        return floatRating
    }

     fun getDailyOverview() {
        Coroutines.main {
            val response = HoroscopeOverviewRepository().horoscopeOverview("Aries")
            if(response.isSuccessful){
                overviewResponse = response.body()
                _overview.value = overviewResponse
                Log.e("response", overviewResponse?.affirmation+"")
            }
        }

    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM