简体   繁体   中英

Fragment livedata observer called only once with default value

I am just not able to figure out what is wrong in this code and why the observer is not called when the value is updated. I am using Fragement with livedata and here is the complete code. When app starts fragment gets it value from default data which in this case is 100. But after the value is updated using queueChannelId(channelId) method the observer is not called. I put a print statement and I can see method is executed in main thread. Please help

Fragment:

override fun onActivityCreated(savedInstanceState: Bundle?) {
    super.onActivityCreated(savedInstanceState)
    viewModel = 
ViewModelProviders.of(this).get(SomeViewModel::class.java)

    viewModel.getChannelId().observe(this, Observer {
        // Only called with default value of mutablelivedata

    })
}

I can assure that onDestroyView and onDestroy have not been called anytime.

ViewModel:

fun getChannelId() : MutableLiveData<Int> {
    return repository.getChannelId()
    }

Repository:

var channelIdObservable = MutableLiveData(100)

fun queueChannelId(channelId: Int) {
    channelIdObservable.value = channelId
}
fun getChannelId() : MutableLiveData<Int> = channelIdObservable

if you are calling queueChannelId from some other Thread try

channelIdObservable.postValue (channelId)

PS: I cant see any other issue here.Share your code of how are u calling queueChannelId .

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