diff --git a/CHANGELOG.md b/CHANGELOG.md index 33e9ca7..82a7573 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,6 +9,7 @@ - Update kotlinx.coroutines to `1.4.3`. - Remove kotlin as `api` dependency. - Remove `ControllerLog.default`. +- Lazily start controller when accessing `Controller.effects` field (#26) ## `[0.13.1]` - 2020-09-13 diff --git a/control-core/src/main/kotlin/at/florianschuster/control/implementation.kt b/control-core/src/main/kotlin/at/florianschuster/control/implementation.kt index 76b21c7..3ad4e67 100644 --- a/control-core/src/main/kotlin/at/florianschuster/control/implementation.kt +++ b/control-core/src/main/kotlin/at/florianschuster/control/implementation.kt @@ -142,6 +142,7 @@ internal class ControllerImplementation( get() = if (stubEnabled) { stubbedEffectFlow.receiveAsFlow().cancellable() } else { + if (controllerStart is ControllerStart.Lazy) start() effectsChannel.receiveAsFlow().cancellable() } diff --git a/control-core/src/test/kotlin/at/florianschuster/control/ImplementationTest.kt b/control-core/src/test/kotlin/at/florianschuster/control/ImplementationTest.kt index f888d01..d394051 100644 --- a/control-core/src/test/kotlin/at/florianschuster/control/ImplementationTest.kt +++ b/control-core/src/test/kotlin/at/florianschuster/control/ImplementationTest.kt @@ -327,6 +327,31 @@ internal class ImplementationTest { sut.cancel() } + @Test + fun `controller is started lazily when only effects field is accessed`() { + val sut = ControllerImplementation( + scope = testCoroutineScope, + dispatcher = testCoroutineScope.defaultScopeDispatcher(), + controllerStart = ControllerStart.Lazy, + initialState = 0, + mutator = { action -> flowOf(action) }, + reducer = { mutation, _ -> mutation }, + actionsTransformer = { actions -> + merge(actions, flow { + emitEffect("actionsTransformer started") + }) + }, + mutationsTransformer = { mutations -> mutations }, + statesTransformer = { states -> states }, + tag = "ImplementationTest.EffectController", + controllerLog = ControllerLog.None + ) + + val effects = sut.effects.testIn(testCoroutineScope) + + effects expect emissions(listOf("actionsTransformer started")) + } + private fun CoroutineScope.createAlwaysSameStateController() = ControllerImplementation( scope = this,