Hi, With the new Kotlin feature Prototype of Conte...
# android
s
Hi, With the new Kotlin feature Prototype of Context Receivers how can we create an extension function for this nesting and make it just one line? I've seen something online but I lost the link.
Copy code
viewLifecycleOwner.lifecycleScope.launch {
    viewLifecycleOwner.repeatOnLifecycle(Lifecycle.State.STARTED) {
        locationProvider.locationFlow().collect {
            // New location! Update the map
        }
    }
 }
s
Hi Sergio, do you mean this:
inline fun <T> Flow<T>.launchAndCollectIn(
owner: LifecycleOwner,
minActiveState: Lifecycle.State = Lifecycle.State.STARTED,
crossinline action: suspend CoroutineScope.(T) -> Unit
) = owner.lifecycleScope.launch {
owner.repeatOnLifecycle(minActiveState) {
collect {
action(it)
}
}
}
Then call from Fragment like this:
Copy code
viewModel.myFlow.launchAndCollectIn(this, Lifecycle.State.STARTED) {
    //nasty stuff
}
There was a similar thing with
repeatingJob
👍 1
s
yes something like that
there's a new context on top context(Fragment) and simplifies it some more
now I'm trying to use this enabling
-Xcontext-receivers
Where do we enable this flags?
s
with the Context stuff you get rid of the owner parameter…
usually inside the gradle project properties (not sure where this parameter belongs)
s
we need beta versions of AS kotlin plugin etc, I'll leave it for now