LiveData used to give callback when lifecycleOwner changed from inactive to active state, therefore we have SingleLiveEvent or Event wrapper as described in this article.
But I am not getting callback on state change if callback was given once, I have created a sample project for same
MainActivity
class MainActivity : AppCompatActivity() {
private val viewModel: MainViewModel by lazy {
ViewModelProvider(this)[MainViewModel::class.java]
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
findViewById<View>(R.id.tv).setOnClickListener {
startActivity(Intent(this, MainActivity2::class.java))
}
viewModel.liveData.observe(this) {
Toast.makeText(this, it, Toast.LENGTH_LONG).show()
}
}
}
ViewModel
class MainViewModel: ViewModel() {
val liveData = MutableLiveData<String>("Random value")
}
In this code, toast is shown when the app launches and it is not shown again if MainActivity2 is started or the app goes to background and then comes back to foreground.