Repeat a task with a time delay?

后端 未结 12 1567
小蘑菇
小蘑菇 2020-11-22 02:14

I have a variable in my code say it is \"status\".

I want to display some text in the application depending on this variable value. This has to be done with a speci

12条回答
  •  余生分开走
    2020-11-22 02:31

    Using kotlin and its Coroutine its quite easy, first declare a job in your class (better in your viewModel) like this:

    private var repeatableJob: Job? = null
    

    then when you want to create and start it do this:

    repeatableJob = viewModelScope.launch {
        while (isActive) {
             delay(5_000)
             loadAlbums(iImageAPI, titleHeader, true)
        }
    }
    repeatableJob?.start()
    

    and if you want to finish it:

    repeatableJob?.cancel()
    

    PS: viewModelScope is only available in view models, you can use other Coroutine scopes such as withContext(Dispatchers.IO)

    More information: Here

提交回复
热议问题