简体   繁体   中英

How to reset the Observable interval operator in RXSwift?

I'm new in RXSwift and i defined an Observable interval timer sequence that calls a webservice method every second. In that webservice response, i receive new retry time value that must replace with my current time. How to reset this sequence with new time value? This is my code :

func mySequence() {

    /////////////////////////////////////// subscribe to Timer (time change)
    var time = try! self.timer.value()

    self.disposeTimer = timer.subscribe({  value in

        time = value.element!

        print("=============================\(String(describing: time))=======================================")

    })
    /////////////////////////////////////// subscribe to Timer (time change)


    let   observable = Observable<Int>.interval(TIME I NEED TO CHANGE After response , scheduler: MainScheduler.instance).map { _ in ()
        self.myWebserviceMethod()
    }

    disposable =  observable.subscribe(onNext: {num in

    }, onError: { err in

    }, onCompleted: {

    }, onDisposed: {

    })

}

everything happens but interval timer time is still the old value :(

Just remove(dispose) old subscription and make new subscription with new interval

var timerDisposable:Disposable?
var retryTime:RxTimeInterval = 1

func stratRefresh() {
    timerDisposable?.dispose()
    timerDisposable = Observable<Int>
        .timer(0, period: retryTime, scheduler: MainScheduler.instance)
        .subscribe(onNext: { value in
            myWebserviceMethod()
        })
}

func myWebserviceMethod() {
    // In service response update your retryTime
    // Ex.
    APIClient.getRetryTime() { newTime in
        if retryTime != newTime {
            retryTime = newTime
            stratRefresh()
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM