Solution 1 :
your LiveData can be referencing MutableLiveData, where you post stuff
private val userMLD = MutableLiveData<List<User>>()
val userLiveData: LiveData<List<User>> = userMLD
and
private fun getUsers() {
val apiHelper = ApiHelper(RetrofitBuilder.apiService)
val mainRepository = MainRepository(apiHelper)
userMLD.postValue(mainRepository.getUsers())
}
Solution 2 :
Instead of creating a LiveData everytime, run your code inside a coroutine and update the LiveData with the new value. You need a MutableLiveData for that:
class MainActivity : AppCompatActivity() {
private val userLiveData = MutableLiveData<List<User>>()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
getUsers() //WORKING <---------
userLiveData.observe(this, Observer {
it.forEach { user ->
Log.i("TAG", user.name)
}
})
lifecycleScope.launch {
delay(5000) //Refresh the result
getUsers() //NOT WORKING <---------
}
}
private fun getUsers() {
val apiHelper = ApiHelper(RetrofitBuilder.apiService)
val mainRepository = MainRepository(apiHelper)
lifecycleScope.launch {
val users = withContext(Dispatchers.IO) {
mainRepository.getUsers() //Suspend function
}
userLiveData.value = users
}
}
}
Problem :
The code below works only once.
class MainActivity : AppCompatActivity() {
lateinit var userLiveData: LiveData<List<User>>
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
getUsers() //WORKING <---------
userLiveData.observe(this, Observer {
it.forEach { user ->
Log.i("TAG", user.name)
}
})
lifecycleScope.launch {
delay(5000) //Refresh the result
getUsers() //NOT WORKING <---------
}
}
private fun getUsers() {
val apiHelper = ApiHelper(RetrofitBuilder.apiService)
val mainRepository = MainRepository(apiHelper)
userLiveData = liveData {
val res = mainRepository.getUsers() //Suspend function
emit(res)
}
}
}
The first time I call the getUsers()
function, I can see the logs. But Later I call getUsers()
, there is no log on the screen.
Which means that the userLiveData.observe(
function runs once.
Comments
Comment posted by IR42
because you create а new livedata but observe an old one
Comment posted by Qwe Qwe
Yes you are right. So how can I run the old one again without destroying it.