Time not updating on RecyclerView using Countdown Timer

34 Views Asked by At

In application have a recyclerview with multiple items and each item have own countdown timer.

Now issue is, countdown timer running only for visible item, other remain item countdown timer running(start) only when item scroll or visible.

I want to start all count down timer of recyclerview item. how I fix it?

Here is code:

class MyBidAdapter(
    private val listener: OnItemClickListener<MyBid>,
    private val userId: Int,
) :
    ListAdapter<MyBid, MyBidAdapter.MyBidViewHolder>(DiffCallback()) {

    private val countdownTimerMap: MutableMap<Int, CountdownTimerUtil> = mutableMapOf()

override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyBidViewHolder {
        val binding = ItemBidBinding.inflate(LayoutInflater.from(parent.context), parent, false)
        return MyBidViewHolder(binding)
    }

    override fun onBindViewHolder(holder: MyBidViewHolder, position: Int) {
        val currentItem = getItem(position)
        holder.bind(currentItem)
    }

    inner class MyBidViewHolder(private val binding: ItemBidBinding) :
        RecyclerView.ViewHolder(binding.root) {

        init {
            binding.apply {
         }
        }

        fun bind(data: MyBid) {
            binding.apply {

                // Cancel the previous CountdownTimerUtil
                countdownTimerMap[position]?.cancel()

                val daysTextView = textView46
                val hoursTextView = textView48
                val minutesTextView = textView50
                val secondsTextView = textView52

                // Calculate total time in milliseconds
                val totalTimeInMillis: Long = data.day.toLong() * 24 * 60 * 60 * 1000 +
                        data.hours.toLong() * 60 * 60 * 1000 +
                        data.minute.toLong() * 60 * 1000 +
                        data.second.toLong() * 1000

                // Ensure that the CountdownTimerUtil is always initialized
                countdownTimerMap[position] = CountdownTimerUtil(
                    totalTimeInMillis, 1000,
                    daysTextView, hoursTextView, minutesTextView, secondsTextView
                ) {
                    // This code will be executed when the countdown finishes
                    button.isEnabled = false
                }
                // Start the timer
                countdownTimerMap[position]?.start()
            }
        }
    }

    class DiffCallback : DiffUtil.ItemCallback<MyBid>() {
        override fun areItemsTheSame(oldItem: MyBid, newItem: MyBid): Boolean {
            return oldItem.id == newItem.id
        }

        override fun areContentsTheSame(oldItem: MyBid, newItem: MyBid): Boolean {
            return oldItem == newItem
        }
    }
}
0

There are 0 best solutions below