Bram Yeh
1 min readNov 22, 2021

As I know, repeatOnLifecycle is a suspend function. If the lifecycle state falls below the target, the coroutine launched for the block is cancelled.

Lastly, the repeatOnLifecycle function itself won’t resume the calling coroutine until the lifecycle is destroyed.

For example from https://medium.com/androiddevelopers/a-safer-way-to-collect-flows-from-android-uis-23080b1f8bda

```

// Create a new coroutine since repeatOnLifecycle is a suspend function

lifecycleScope.launch {

// The block passed to repeatOnLifecycle is executed when the lifecycle

// is at least STARTED and is cancelled when the lifecycle is STOPPED.

// It automatically restarts the block when the lifecycle is STARTED again.

repeatOnLifecycle(Lifecycle.State.STARTED) {

// Safely collect from locationFlow when the lifecycle is STARTED

// and stops collection when the lifecycle is STOPPED

locationProvider.locationFlow().collect {

// New location! Update the map

}

}

}

```

Since repeatOnLifecycle stops and restarts the flow collection when the lifecycle moves in and out of the target state, I think we needn't cancelling the upstream flow, because it will auto cancel when there is no active observer.

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

Bram Yeh
Bram Yeh

Written by Bram Yeh

Lead Android & iOS Mobile Engineer at Yahoo (Verizon Media) Taiwan https://www.linkedin.com/in/hanruyeh/

Responses (1)

Write a response

But, if the flow comes from an external source, such as some DB or repository, to automatically cancel the flow when ViewModel becomes destroyed, it’s better (or we prefer) to use asLiveData(viewModelScope.coroutineContext).
yeah my point was , for…

--