Stateflow collect multiple times inside each button click event. How to resolve this issue?

Issue

This Content is from Stack Overflow. Question asked by sriram D

I checked and found that collects have been increased two times by each click . I don’t know what is the cause and what is the remedy for below code . I am a beginner in Android dev and this issue becomes a headache for me.

 binding.downloadBtn.setOnClickListener {
        var count = 0
            if (id != null) {       
                viewModel.getDownloads(id)
            }
          lifecycleScope.launch{
                viewModel.getDownloads.collect {
                    count++
                    Log.i("torrent movies", "count ${count} and download ${it}")               
                    if (downloads!=null) {
                        bundle.putParcelable(Constants.DOWNLOADS, downloads)
                       findNavController()
                            .navigate(R.id.action_movieDetailsFragment_to_downloadFragment, bundle)
                    }
                }
            }



Solution

This question is not yet answered, be the first one who answer using the comment. Later the confirmed answer will be published as the solution.

This Question and Answer are collected from stackoverflow and tested by JTuto community, is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.

people found this article helpful. What about you?