flamyoad / Honnoki

ほんの木
16 stars 3 forks source link

Lifecycle.repeatOnLifecycle ???????? #10

Closed flamyoad closed 3 years ago

flamyoad commented 3 years ago

?????????

?!?

A cold flow backed by a channel or using operators with buffers such as buffer, conflate, flowOn, or shareIn is not safe to collect with some of the existing APIs such as CoroutineScope.launch, Flow<T>.launchIn, or LifecycleCoroutineScope.launchWhenX, unless you manually cancel the Job that started the coroutine when the activity goes to the background. These APIs will keep the underlying flow producer active while emitting items into the buffer in the background, and thus wasting resources.

class LocationActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        lifecycleScope.launch {
            someLocationProvider.locations
                .flowWithLifecycle(lifecycle, STARTED).  <------- ??????
                .collect {  }
        }
    }
}

LiveData.observe() automatically unregisters the consumer when the view goes to the STOPPED state, whereas collecting from a StateFlow or any other flow does not stop collecting automatically. To achieve the same behavior,you need to collect the flow from a Lifecycle.repeatOnLifecycle block.

flamyoad commented 3 years ago

https://www.reddit.com/r/androiddev/comments/mck4hq/a_safer_way_to_collect_flows_from_android_uis/

flamyoad commented 3 years ago

Similarly, the Flow.stateIn and Flow.shareIn operators can be configured with the sharing started policy for this. WhileSubscribed() will stop the underlying producer when there are no active observers! On the contrary,Eagerly or Lazily will keep the underlying producer active as long as the CoroutineScope they use is active.

flamyoad commented 3 years ago

https://medium.com/swlh/deep-dive-into-lifecycle-coroutines-e7192312faf#7d09