Coroutine scope for Presenters #696
-
Coming from typical MVVM architecture, Android ViewModels provide Presenters don't have any kind of lifecycle, right? So there is nowhere to cancel a coroutine context. I've seen in the sample apps that sometimes the I am thinking that maybe the right way to do this would be to just create a scope that is shared across presenters and have that injected to the presenter. Anyone else with more Circuit or DI experience have any better ideas than what I've outlined in the example below? If that is a good approach, any tips on making a coroutine scope for this kind of thing? Anything I need to avoid to make sure I'm not leaking memory in my presenters? Thanks in advance! interface WidgetRepository {
val widget: StateFlow<Widget?>
suspend fun createWidget(): Widget
}
@Parcelize
object WidgetScreen : Screen {
data class State(
val widget: Widget?,
val widgetLoading: Boolean,
val eventSink: (Event) -> Unit
) : CircuitUiState
sealed interface Event : CircuitUiEvent {
object ClickCreateWidget : Event
}
}
class WidgetPresenter @Inject constructor(
private val widgetRepo: WidgetRepository,
@PresenterScope private val presenterScope: CoroutineScope,
) : Presenter<WidgetScreen.State> {
@Composable
override fun present(): WidgetScreen.State {
val widget: Widget? by widgetRepo.widget.collectAsState()
var widgetLoading by remember { mutableStateOf(false) }
return WidgetScreen.State(
widget = widget,
widgetLoading = widgetLoading,
) { event ->
when (event) {
WidgetScreen.Event.ClickCreateWidget -> presenterScope.launch {
widgetLoading = true
widgetRepo.createWidget()
widgetLoading = false
}
}
}
}
} |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 11 replies
-
Presenters aren't retained on configuration changes, for scoping you should just use the native CoroutineScope APIs that compose itself offers. |
Beta Was this translation helpful? Give feedback.
Presenters aren't retained on configuration changes, for scoping you should just use the native CoroutineScope APIs that compose itself offers.