DEV Community

HarmonyOS
HarmonyOS

Posted on

How to Listen for Live View Timer Countdown Completion and Close the Live View

Read the original article:How to Listen for Live View Timer Countdown Completion and Close the Live View

How to Listen for Live View Timer Countdown Completion and Close the Live View

Context

When using the Live View Service in HarmonyOS, developers may need to detect when a countdown timer in a live view has finished and then automatically close the live view window.

Description

The issue is how to listen for the end event of the live view timer countdown and ensure that the live view closes correctly when the countdown reaches zero.

Solution / Approach

  1. When calling liveViewManager.startLiveView, record the current timestamp as the start time.
  2. Retrieve the countdown time from the live view request body (liveView.timer?.time).
  3. Start a loop that continuously checks whether the current time minus the start time is still less than the countdown time.
  4. If the condition is no longer satisfied (countdown finished), call liveViewManager.stopLiveView() to close the live view.
liveViewManager.startLiveView(liveView).then((liveViewResult: liveViewManager.LiveViewResult) => {
  // Record start time
  this.start = new Date().getTime();
  // Retrieve countdown time from the request body
  this.time = liveView.timer?.time
}).catch((err: BusinessError) => {
  // Handle error
})

// Loop to check countdown
async countDown() {
  if (this.time) {
    while (new Date().getTime() - this.start < this.time) {
      await this.sleep(1000)
    }
    liveViewManager.stopLiveView()
  }
}

// Sleep helper
sleep(ms: number): Promise<void> {
  return new Promise(resolve => setTimeout(resolve, ms));
}
Enter fullscreen mode Exit fullscreen mode

Key Takeaways

  • Track the start time when creating the live view.
  • Continuously compare the elapsed time with the countdown duration.
  • Use liveViewManager.stopLiveView() to close the window once the timer finishes.

Additional Resources

Written by Bunyamin Eymen Alagoz

Top comments (0)