[SOLVED] 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

Your count variable and viewModel.getDownloads.collect {} this code should be outside of onClick(). In your current code everytime user is performing click we are setting the collect


This Question was asked in StackOverflow by sriram D and Answered by Ashutosh Ojha It 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?