Reputation: 482
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 ?
Upvotes: 0
Views: 752
Reputation: 81578
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.
Upvotes: 1
Reputation: 7690
As long as you don't keep a subscription to the old livedata, it should should become inactive. See LiveData.onInactive() for more information
Upvotes: 1