0

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.

Parth Gupta
  • 69
  • 1
  • 5
  • You don't have changes that's why you're not getting toast... If you've updates it'll emit. And From 2nd activity to comes back 1st activity it won't emit... You need changes on their livedata – Gobu CSG Aug 23 '22 at 20:23
  • Yes, this is happening but if you go through this [article](https://medium.com/androiddevelopers/livedata-with-snackbar-navigation-and-other-events-the-singleliveevent-case-ac2622673150) we have to specially handle these cases but now they are handled automatically. Is this handled in LiveData after some version? and we don't need `Event` wrapper class – Parth Gupta Aug 24 '22 at 05:55

0 Answers0