while true in Coroutine LiveData

I'm using coroutine livedata to do some stuff every 4 seconds. This is the code I used

val reloadInterval: MutableLiveData<Long> = MutableLiveData()
val data = reloadInterval.switchMap { delay ->
    liveData(Dispatchers.IO) {
        while (true) {
            delay(delay)
            emit(data)
        }
    }
}

fun reloadInterval(interval: Long) {
    reloadInterval.value = interval
}

So my question is when I change the reloadInterval value the switchMap flow get triggered and return a new livedata then will the old livedata still running or it will stopped automatically ?

2 answers

  • answered 2021-01-11 07:32 Nagy Robi

    As long as you don't keep a subscription to the old livedata, it should should become inactive. See LiveData.onInactive() for more information

  • answered 2021-01-11 07:36 EpicPandaForce

    The liveData { coroutine builder's block is only executed while the LiveData is active. The block runner is cancelled after a given timeout period, which is by default 5 seconds.

    So while(true) { will stop after 5 seconds. You can pass liveData(timeoutInMs = 0) { to immediately terminate the loop.