Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Timer.TimerPublisher doesn’t fire while scrolling

I tried to make a timer on SwiftUI, which worked just fine:

import SwiftUI
import Combine    
struct ContentView: View {
let currentTimePublisher  = Timer.TimerPublisher(interval: 1.0, runLoop: .main, mode: .default)
    .autoconnect()

@State private var currentTime = Date()
var body: some View {

    VStack{
        Text("Time is:")
        Text("\(currentTime)")
        }.onReceive(currentTimePublisher) { (date) in
            self.currentTime = date
        }
    }
}

However, I tried to put the VStack in anything scrollable, be List, or ScrollView, I was not updating when I was scrolling the screen. It worked just fine when I didn't scroll.

I also put the TimerPublisher on the main thread as you can see, but that didn't change anything.

How can I make the SwiftUI update the time while I'm scrolling/interacting?

like image 578
Hamoonist Avatar asked Dec 22 '22 21:12

Hamoonist


1 Answers

The scroll view runs the run loop in a different mode (not .default) while tracking touches. Use mode .common instead of mode .default to schedule the timer in the “common” run loop modes, which includes the scroll-tracking mode:

let currentTimePublisher  = Timer.TimerPublisher(interval: 1.0, runLoop: .main, mode: .common)
    .autoconnect()
like image 71
rob mayoff Avatar answered Jan 08 '23 02:01

rob mayoff