### Comprehensive Testing Example Source: https://orbit-mvi.org/Test This example demonstrates a complete test scenario, combining initialization, `onCreate` execution, intent invocation, and assertions for both states and side effects. It ensures all interactions and outcomes are verified. ```kotlin @Test fun exampleTest() = runTest { ExampleViewModel().test(this) { runOnCreate() containerHost.countToFour() expectState { copy(count = 1) } expectSideEffect(Toast(1)) expectState { copy(count = 2) } expectSideEffect(Toast(2)) expectState { copy(count = 3) } expectSideEffect(Toast(3)) expectState { copy(count = 4) } expectSideEffect(Toast(4)) } } ``` -------------------------------- ### Container Creation API Source: https://orbit-mvi.org/dokka/orbit-core/org.orbitmvi.orbit/container Provides details on how to create a new Orbit MVI container with initial state and optional setup. ```APIDOC ## Container Creation ### Description Helps create a concrete container in a standard way. ### Method `container` (function) ### Endpoint N/A (This is a function call within a CoroutineScope) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None **Parameters for `container` function:** - **initialState** (STATE) - Required - The initial state of the container. - **buildSettings** (SettingsBuilder.() -> Unit) - Optional - A lambda to configure the container's settings. - **onCreate** (suspend Syntax.() -> Unit?) - Optional - A lambda to execute when the container is created. By default, it's executed lazily upon first interaction. ### Request Example ```kotlin coroutineScope.container( initialState = MyState.Initial, buildSettings = { // Configure settings here if needed }, onCreate = { // Code to run on container creation // postSideEffect(MySideEffect.ShowToast("Container created!")) } ) ``` ### Response #### Success Response - **Container** - A Container implementation that manages state and side effects. ``` -------------------------------- ### Initialize Container for Testing Source: https://orbit-mvi.org/Test Initialize your ContainerHost in test mode using the `test()` function. You can optionally provide an initial state to seed the container, simplifying test setup by avoiding the need to call multiple intents to reach a desired state. ```kotlin data class State(val count: Int = 0) @Test fun exampleTest() = runTest { ExampleViewModel().test(this, State()) { containerHost.countToFour() // await states and side effects, perform assertions } } ``` -------------------------------- ### Orbit Container and State/Side Effect Handling (Kotlin) Source: https://orbit-mvi.org/Core Demonstrates the setup of an Orbit Container, defining state and side effects, and subscribing to state and side effect flows. This is a core pattern for managing UI state and events in Orbit. ```kotlin data class ExampleState(val seen: List = emptyList()) sealed class ExampleSideEffect { data class Toast(val text: String) } class ExampleContainerHost(scope: CoroutineScope) : ContainerHost { // create a container override val container = scope.container(ExampleState()) fun doSomethingUseful() = intent { ... } } private val scope = CoroutineScope(Dispatchers.Main) private val viewModel = ExampleContainerHost(scope) fun main() { // subscribe to updates // On Android, use ContainerHost.observe() from the orbit-viewmodel module scope.launch { viewModel.container.stateFlow.collect { // do something with the state } } scope.launch { viewModel.container.sideEffectFlow.collect { // do something with the side effect } } viewModel.doSomethingUseful() // Ensure the main function does not complete so we can do something useful with the container. } ``` -------------------------------- ### Orbit Transformation Operator Example (Kotlin) Source: https://orbit-mvi.org/Core Illustrates the use of the 'intent' block and suspend function calls for transformations within Orbit. This is how you perform asynchronous operations and data manipulation. ```kotlin class Example : ContainerHost { ... fun simpleExample() = intent { anotherApiCall(apiCall()) // just call suspending functions } } ``` -------------------------------- ### Getting All Subscription Values as Array (Kotlin) Source: https://orbit-mvi.org/dokka/orbit-core/org.orbitmvi.orbit.internal.repeatonsubscription/-subscription/index Shows how to obtain an array containing all the constants of the Subscription enum. The 'values' function returns these in the order they were declared. ```kotlin val allSubscriptionValues: Array = Subscription.values() ``` -------------------------------- ### Kotlin: subIntent for Parallel Decomposition Source: https://orbit-mvi.org/dokka/orbit-core/org.orbitmvi.orbit/-container-host/sub-intent Demonstrates the usage of the subIntent function in Kotlin for parallel decomposition of intents. This example shows how to launch multiple sub-intents concurrently using coroutineScope, with each sub-intent collecting from a different flow and posting side effects. ```kotlin override val container = scope.container(initialState) { coroutineScope { launch { sendSideEffect1() } launch { sendSideEffect2() } } } @OptIn(OrbitExperimental::class) private suspend fun sendSideEffect1() = subIntent { flow1.collect { postSideEffect(it) } } @OptIn(OrbitExperimental::class) private suspend fun sendSideEffect1() = subIntent { flow2.collect { postSideEffect(it) } } ``` -------------------------------- ### repeatOnSubscription Source: https://orbit-mvi.org/dokka/orbit-core/org.orbitmvi.orbit.syntax/-sub-state-syntax/repeat-on-subscription Starts and stops a coroutine block based on the number of subscribers to Container.refCountStateFlow and Container.refCountSideEffectFlow. ```APIDOC ## repeatOnSubscription ### Description Starts and stops the provided block of code based on the number of subscribers to the Container.refCountStateFlow and Container.refCountSideEffectFlow. If the number of subscribers reaches non-zero, the block is run. When the number of subscribers reaches zero, the block is cancelled after a short delay. The delay can be set when creating the Container using SettingsBuilder.repeatOnSubscribedStopTimeout. This API is useful for collecting hot flows. ### Method Suspend Function (Kotlin Coroutines) ### Endpoint N/A (This is a Kotlin function, not a REST endpoint) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```kotlin container.repeatOnSubscription { // Code to run when there are active subscribers collectLatest(someFlow) { value -> /* ... */ } } ``` ### Response #### Success Response N/A (This is a function that executes coroutines, not a request/response API) #### Response Example N/A ``` -------------------------------- ### GET /websites/orbit-mvi/values Source: https://orbit-mvi.org/dokka/orbit-core/org.orbitmvi.orbit.internal.repeatonsubscription/-subscription/values Retrieves an array of all available Subscription enum values. This can be used for iteration or to understand the available subscription types. ```APIDOC ## GET /websites/orbit-mvi/values ### Description Returns an array containing the constants of the Subscription enum type, in the order they're declared. This method may be used to iterate over the constants. ### Method GET ### Endpoint /websites/orbit-mvi/values ### Parameters #### Path Parameters None #### Query Parameters None ### Request Example ```json {} ``` ### Response #### Success Response (200) - **values** (Array) - An array of Subscription enum constants. #### Response Example ```json { "values": [ "FREE", "BASIC", "PREMIUM" ] } ``` ``` -------------------------------- ### TextField State Hoisting with ViewModel Source: https://orbit-mvi.org/Compose Manage TextField state within your ViewModel for validation and other logic. This example shows how to use `TextFieldState` and observe changes using `snapshotFlow` to update the UI state, preventing input loss. ```kotlin class TextViewModel : ViewModel(), ContainerHost { override val container: Container = container(State()) { coroutineScope { launch { snapshotFlow { state.textFieldState.text }.collectLatest { text -> reduce { state.copy(isValid = text.isValid()) } } } } } data class State( val textFieldState: TextFieldState = TextFieldState(""), val isValid: Boolean = false, ) companion object { fun CharSequence.isValid(): Boolean { return this.isNotBlank() && this.length <= 10 } } } ``` -------------------------------- ### Subscribe to ContainerHost in Compose Source: https://orbit-mvi.org/Compose This Composable function demonstrates how to subscribe to a ContainerHost's state and side effects within the Compose UI lifecycle. It ensures subscriptions are managed safely, only activating when the view is at least STARTED. ```kotlin @Composable fun SomeScreen(viewModel: SomeViewModel) { val state by viewModel.collectAsState() viewModel.collectSideEffect { when(it) { ... } } SomeContent( state = state ) } ``` -------------------------------- ### Handle Unconsumed States and Side Effects in Orbit MVI Tests Source: https://orbit-mvi.org/Test This example shows how to handle unconsumed states and side effects at the end of an Orbit MVI test. If not explicitly handled, unconsumed items will cause the test to fail. Use `skip(n)` to ignore a specific number of items or `cancelAndIgnoreRemainingItems()` to ignore all remaining items. ```kotlin @Test fun exampleTest() = runTest { ExampleViewModel().test(this) { runOnCreate() containerHost.countToFour() expectState { copy(count = 1) } expectSideEffect(Toast(1)) // Deal with unconsumed items that were emitted by the container skip(4) // OR ignore all unconsumed items cancelAndIgnoreRemainingItems() } } ``` -------------------------------- ### SubStateContainerContext Constructor (Kotlin) Source: https://orbit-mvi.org/dokka/orbit-core/org.orbitmvi.orbit.syntax/-sub-state-container-context/index Initializes a new instance of the SubStateContainerContext class. It requires instances of RealSettings, a postSideEffect function, a getState function, a reduce function, and a SubscribedCounter. ```kotlin SubStateContainerContext( settings = RealSettings(...), postSideEffect = { sideEffect -> /* handle side effect */ }, getState = { /* return current state */ }, reduce = { reducer -> /* apply reducer */ }, subscribedCounter = SubscribedCounter() ) ``` -------------------------------- ### Getting Subscription Ordinal Value (Kotlin) Source: https://orbit-mvi.org/dokka/orbit-core/org.orbitmvi.orbit.internal.repeatonsubscription/-subscription/index Demonstrates how to get the ordinal (positional) value of a Subscription enum constant. The 'ordinal' property returns the zero-based index of the enum constant. ```kotlin val subscription: Subscription = Subscription.Subscribed val subscriptionOrdinal: Int = subscription.ordinal ``` -------------------------------- ### RealSettings Constructor Parameters Source: https://orbit-mvi.org/dokka/orbit-core/org.orbitmvi.orbit/-real-settings/-real-settings The constructor for RealSettings allows customization of various aspects of its operation. Parameters include buffer sizes for side effects, an idling registry for testing, dispatchers for event loops and intent launching, an optional exception handler, and a timeout for repeat-on-subscribed behavior. ```kotlin constructor( sideEffectBufferSize: Int = Channel.BUFFERED, idlingRegistry: IdlingResource = NoopIdlingResource(), eventLoopDispatcher: CoroutineDispatcher = Dispatchers.Default, intentLaunchingDispatcher: CoroutineDispatcher = Dispatchers.Unconfined, exceptionHandler: CoroutineExceptionHandler? = null, repeatOnSubscribedStopTimeout: Long = 100)(source) ``` -------------------------------- ### SubStateSyntax Constructors Source: https://orbit-mvi.org/dokka/orbit-core/org.orbitmvi.orbit.syntax/-sub-state-syntax/index Provides information about the constructors available for the SubStateSyntax class. ```APIDOC ## SubStateSyntax Constructor ### Description Initializes a new instance of the SubStateSyntax class. ### Method CONSTRUCTOR ### Endpoint N/A ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```json { "example": "Not applicable for constructor" } ``` ### Response #### Success Response (200) N/A #### Response Example ```json { "example": "Not applicable for constructor" } ``` ``` -------------------------------- ### Initialize RealSettings Source: https://orbit-mvi.org/dokka/orbit-core/org.orbitmvi.orbit.internal/-test-container-decorator/settings This snippet shows the initialization of the RealSettings object, which holds the settings the container was configured with. It takes a source as a parameter. ```kotlin open override val settings: RealSettings(source) ``` -------------------------------- ### OrbitTestContext - runOnCreate Source: https://orbit-mvi.org/dokka/orbit-test/org.orbitmvi.orbit.test/-orbit-test-context/index Invokes the `onCreate` lambda for the ContainerHost. ```APIDOC ## POST /websites/orbit-mvi/runOnCreate ### Description Invokes the `onCreate` lambda for the ContainerHost. ### Method POST ### Endpoint /websites/orbit-mvi/runOnCreate ### Parameters #### Query Parameters None #### Request Body None ### Response #### Success Response (200) - **Job** (object) - A Job representing the execution of the onCreate lambda. #### Response Example ```json { "jobId": "some-job-id" } ``` ``` -------------------------------- ### container Function Source: https://orbit-mvi.org/dokka/orbit-core/org.orbitmvi.orbit/index A factory function to create a new Orbit MVI container with specified initial state and optional setup logic. ```APIDOC ## container Function ### Description Helps create a concrete container in a standard way. ### Method `fun CoroutineScope.container( initialState: STATE, buildSettings: SettingsBuilder.() -> Unit = {}, onCreate: suspend Syntax.() -> Unit? = null ): Container` ### Parameters #### Query Parameters - **initialState** (STATE) - Required - The initial state of the container. - **buildSettings** (SettingsBuilder.() -> Unit) - Optional - A lambda to configure container settings. - **onCreate** (suspend Syntax.() -> Unit?) - Optional - A suspend lambda to run when the container is created. ``` -------------------------------- ### NoopIdlingResource Constructor (Kotlin) Source: https://orbit-mvi.org/dokka/orbit-core/org.orbitmvi.orbit.idling/-noop-idling-resource/index The NoopIdlingResource class has a default constructor that takes no arguments. This constructor initializes a NoopIdlingResource instance. ```kotlin class NoopIdlingResource : IdlingResource(source) constructor() ``` -------------------------------- ### Getting Subscription Name (Kotlin) Source: https://orbit-mvi.org/dokka/orbit-core/org.orbitmvi.orbit.internal.repeatonsubscription/-subscription/index Shows how to retrieve the string name of a Subscription enum constant. The 'name' property provides the identifier used when declaring the enum constant. ```kotlin val subscription: Subscription = Subscription.Subscribed val subscriptionName: String = subscription.name ``` -------------------------------- ### Observe State and Side Effects Source: https://orbit-mvi.org/dokka/orbit-viewmodel/org.orbitmvi.orbit.viewmodel/observe Observe the stateFlow and sideEffectFlow of a ContainerHost. The observation is tied to the lifecycle of the provided LifecycleOwner and starts when the lifecycle reaches the specified Lifecycle.State. ```APIDOC ## observe ### Description Observe Container.stateFlow and Container.sideEffectFlow correctly on Android in one-line of code. These streams are observed when the view is in Lifecycle.State.STARTED. ### Method Extension Function (Kotlin) ### Endpoint N/A (Kotlin Extension Function) ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Request Example **In Activities:** ```kotlin viewModel.observe(this, state = ::state, sideEffect = ::sideEffect) ``` **In Fragments:** ```kotlin viewModel.observe(viewLifecycleOwner, state = ::state, sideEffect = ::sideEffect) ``` ### Response #### Success Response N/A (This is an observation function, it does not return a value directly but executes callbacks.) #### Response Example N/A ``` -------------------------------- ### Instantiate Orbit MVI Container in Kotlin Source: https://orbit-mvi.org/dokka/orbit-core/org.orbitmvi.orbit/-container-host/container Demonstrates how to instantiate the Orbit MVI Container using a scope and a factory function. This requires defining the state and side effect types for the container. ```kotlin override val container = scope.container(initialState) ``` -------------------------------- ### Get Enum Constant by Name in Kotlin Source: https://orbit-mvi.org/dokka/orbit-core/org.orbitmvi.orbit.internal.repeatonsubscription/-subscription/value-of The 'valueOf()' function in Kotlin retrieves an enum constant by its exact name. It is case-sensitive and does not permit extraneous whitespace. An IllegalArgumentException is thrown if no constant matches the provided name. ```kotlin enum class Color { RED, GREEN, BLUE } fun main() { val color = Color.valueOf("RED") println(color) // Output: RED try { Color.valueOf("YELLOW") } catch (e: IllegalArgumentException) { println(e.message) // Output: No enum constant Color.YELLOW } } ``` -------------------------------- ### expectInitialState Function Source: https://orbit-mvi.org/dokka/orbit-test/org.orbitmvi.orbit.test/-orbit-test-context/expect-initial-state Details about the expectInitialState function, its purpose, and how to handle its deprecation. ```APIDOC ## expectInitialState ### Description Sanity check assertion. Checks if the initial state is emitted and matches the initial state defined for the production container (or the one specified in the test). ### Deprecated Initial state is now checked automatically. If you wish to manually verify the initial state, use `autoCheckInitialState=false` in test settings and use `expectState` or `awaitState`. ### Throws AssertionError if initial state does not match. ``` -------------------------------- ### Accessing Subscription Enum Entries (Kotlin) Source: https://orbit-mvi.org/dokka/orbit-core/org.orbitmvi.orbit.internal.repeatonsubscription/-subscription/index Demonstrates how to access all available entries of the Subscription enum. This is useful for iterating through all possible subscription states. ```kotlin val allSubscriptions: EnumEntries = Subscription.entries ``` -------------------------------- ### ContainerContext Constructor Source: https://orbit-mvi.org/dokka/orbit-core/org.orbitmvi.orbit.syntax/-container-context/index Initializes a new instance of the ContainerContext class with the provided settings, side effect posting function, state reduction function, subscribed counter, and state flow. ```APIDOC ## ContainerContext Constructor ### Description Initializes a new instance of the ContainerContext class. ### Method Constructor ### Parameters - **settings** (RealSettings) - The real settings for the container. - **postSideEffect** (suspend (SE) -> Unit) - A function to post side effects. - **reduce** (suspend ((S) -> S) -> Unit) - A function to reduce the state. - **subscribedCounter** (SubscribedCounter) - A counter for subscriptions. - **stateFlow** (StateFlow) - The state flow of the container. ### Request Example ```kotlin val containerContext = ContainerContext( settings = realSettings, postSideEffect = { sideEffect -> /* handle side effect */ }, reduce = { reducer -> /* apply state reduction */ }, subscribedCounter = subscribedCounter, stateFlow = stateFlow ) ``` ### Response #### Success Response (200) - **ContainerContext** (ContainerContext) - The newly created ContainerContext instance. #### Response Example ```json { "message": "ContainerContext initialized successfully" } ``` ``` -------------------------------- ### Repeat Coroutine on Subscription (Kotlin) Source: https://orbit-mvi.org/dokka/orbit-core/org.orbitmvi.orbit.syntax/-syntax/repeat-on-subscription Starts and stops a suspend block based on the number of subscribers to a container's refCountStateFlow and refCountSideEffectFlow. The block runs when subscribers are non-zero and is cancelled after a delay when subscribers reach zero. Useful for collecting hot flows. ```kotlin suspend fun repeatOnSubscription(block: suspend CoroutineScope.() -> Unit)(source) Starts and stops the provided block of code based on the number of subscribers to the Container.refCountStateFlow and Container.refCountSideEffectFlow. If the number of subscribers reaches non-zero, the block is run. When the number of subscribers reaches zero, the block is cancelled after a short delay. The delay can be set when creating the Container using SettingsBuilder.repeatOnSubscribedStopTimeout. This API is useful for collecting hot flows. #### Parameters _block_ the lambda to run when we have active subscribers. ``` -------------------------------- ### Orbit ContainerHost with Android ViewModel (Kotlin) Source: https://orbit-mvi.org/Core Shows how to integrate Orbit's ContainerHost with an Android ViewModel. This allows you to leverage Orbit's MVI patterns within the Android architecture. ```kotlin class ExampleViewModel( savedStateHandle: SavedStateHandle ) : ViewModel(), ContainerHost { // create a container val container = container(ExampleState(), savedStateHandle) … } ``` -------------------------------- ### SubStateContainerContext Properties (Kotlin) Source: https://orbit-mvi.org/dokka/orbit-core/org.orbitmvi.orbit.syntax/-sub-state-container-context/index Defines the properties of the SubStateContainerContext class. These include settings for configuration, postSideEffect for handling side effects, reduce for state transitions, the current state, and a subscribedCounter. ```kotlin val postSideEffect: suspend (SE) -> Unit val reduce: suspend ((T) -> S) -> Unit val settings: RealSettings val state: T val subscribedCounter: SubscribedCounter ``` -------------------------------- ### Collect Side Effects in Compose with Orbit MVI Source: https://orbit-mvi.org/dokka/orbit-compose/org.orbitmvi.orbit.compose/collect-side-effect Collects Container.sideEffectFlow within a Compose LaunchedEffect. The collection is active when the component's lifecycle state matches the provided lifecycleState, defaulting to STARTED. This ensures side effects are processed only when the UI is in an appropriate state. ```kotlin import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.lifecycle.Lifecycle import org.orbitmvi.orbit.ContainerHost @Composable fun ContainerHost.collectSideEffect( lifecycleState: Lifecycle.State = Lifecycle.State.STARTED, sideEffect: suspend (sideEffect: SIDE_EFFECT) -> Unit ) { LaunchedEffect(Unit) { containerHost.sideEffectFlow.collect { sideEffect(it) } } } ``` -------------------------------- ### RealSettings Constructor Source: https://orbit-mvi.org/dokka/orbit-core/org.orbitmvi.orbit/-real-settings/-real-settings Details the parameters for the RealSettings constructor, which is used to configure side effect buffer size, idling resources, dispatchers, and exception handling. ```APIDOC ## RealSettings Constructor ### Description Initializes the RealSettings with configurable parameters for managing side effects, idling resources, coroutine dispatchers, and exception handling. ### Method Constructor ### Endpoint N/A (Constructor) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```kotlin RealSettings( sideEffectBufferSize = Channel.BUFFERED, idlingRegistry = NoopIdlingResource(), eventLoopDispatcher = Dispatchers.Default, intentLaunchingDispatcher = Dispatchers.Unconfined, exceptionHandler = null, repeatOnSubscribedStopTimeout = 100 ) ``` ### Response #### Success Response (N/A) N/A #### Response Example N/A ### Parameters * **sideEffectBufferSize** (Int) - Optional - The buffer size for side effects. Defaults to `Channel.BUFFERED`. * **idlingRegistry** (IdlingResource) - Optional - An IdlingResource for tracking background work. Defaults to `NoopIdlingResource()`. * **eventLoopDispatcher** (CoroutineDispatcher) - Optional - The dispatcher for the event loop. Defaults to `Dispatchers.Default`. * **intentLaunchingDispatcher** (CoroutineDispatcher) - Optional - The dispatcher for launching intents. Defaults to `Dispatchers.Unconfined`. * **exceptionHandler** (CoroutineExceptionHandler?) - Optional - A handler for coroutine exceptions. Defaults to `null`. * **repeatOnSubscribedStopTimeout** (Long) - Optional - Timeout for stopping when repeated on subscription. Defaults to `100`. ``` -------------------------------- ### Observe Multiple Flows on Container Subscription in Kotlin Source: https://orbit-mvi.org/Core Orbit MVI's container factories support observing multiple flows upon subscription using `coroutineScope` and `repeatOnSubscription`. This pattern is useful for starting asynchronous operations, like collecting data from flows, immediately after the container is created and subscribed to. ```kotlin perform("Toast the current state") class Example( private val flow1: Flow, private val flow2: Flow, ): ContainerHost { override val container = container(ExampleState()) { coroutineScope { repeatOnSubscription { launch { flow1.collect { reduce { ... } } launch { flow2.collect { reduce { ... } } } } } } ``` -------------------------------- ### Test Infinite Flow Collection with Finite Flow Replacement (Kotlin) Source: https://orbit-mvi.org/Test Demonstrates replacing an infinite flow with a finite one for simpler testing of Orbit MVI containers. It shows how to set up a container, collect updates, and assert states within a test environment. ```kotlin val container = scope.container { intent { runOnSubscription { locationService.locationUpdates.collect { reduce { state.copy(lng = it.lng, lat = it.lat) } } } } } ``` -------------------------------- ### Repeat Flow Collection on Subscription with Orbit MVI Source: https://orbit-mvi.org/Core The `repeatOnSubscription` block allows you to collect flows only when the UI is actively observing state or side effect streams. This prevents unnecessary work for expensive flows when the UI is not visible. The collection automatically starts when an observer subscribes and stops when the last observer unsubscribes. ```kotlin class Example : ContainerHost { ... fun simpleExample() = intent(idlingResource = false) { repeatOnSubscription { expensiveFlow().collect { // } } } } ``` -------------------------------- ### AndroidIdlingResource Constructor Source: https://orbit-mvi.org/dokka/orbit-viewmodel/org.orbitmvi.orbit.viewmodel/-android-idling-resource/index Initializes a new instance of the AndroidIdlingResource class. ```APIDOC ## Constructor AndroidIdlingResource ### Description Initializes a new instance of the AndroidIdlingResource class. ### Method CONSTRUCTOR ### Endpoint N/A ### Parameters None ### Request Example N/A ### Response #### Success Response (200) N/A #### Response Example N/A ``` -------------------------------- ### RefCountStateFlow Usage Source: https://orbit-mvi.org/dokka/orbit-core/org.orbitmvi.orbit/-container/ref-count-state-flow Demonstrates the usage of refCountStateFlow, a ref-counted StateFlow designed for specific subscription scenarios. ```APIDOC ## RefCountStateFlow ### Description A version of stateFlow ref-counted for the Syntax.repeatOnSubscription operator. Do not use when subscribing to state updates within your ContainerHost. A StateFlow of state updates. Emits the latest state upon subscription and serves only distinct values (through equality comparison). ### Method N/A (This is a property/declaration, not an endpoint) ### Endpoint N/A ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Request Example N/A ### Response #### Success Response (200) N/A #### Response Example N/A ``` -------------------------------- ### ContainerContext Constructor Initialization (Kotlin) Source: https://orbit-mvi.org/dokka/orbit-core/org.orbitmvi.orbit.syntax/-container-context/-container-context Initializes the ContainerContext with necessary dependencies for managing state and side effects in Orbit MVI. It takes settings, side effect handling, state reduction, a subscription counter, and the state flow as parameters. ```kotlin constructor( settings: RealSettings, postSideEffect: suspend (SE) -> Unit, reduce: suspend ((S) -> S) -> Unit, subscribedCounter: SubscribedCounter, stateFlow: StateFlow )(source) ``` -------------------------------- ### TestSettings Constructor and Properties Source: https://orbit-mvi.org/dokka/orbit-test/org.orbitmvi.orbit.test/-test-settings/index This section details the constructor and properties of the TestSettings data class, which allows for overriding CoroutineDispatchers, CoroutineExceptionHandlers, and controlling the auto-check of the initial state during tests. ```APIDOC ## TestSettings ### Description Represents settings for configuring tests, allowing overrides for dispatchers, exception handlers, and initial state checks. ### Constructor `TestSettings(dispatcherOverride: CoroutineDispatcher? = null, exceptionHandlerOverride: CoroutineExceptionHandler? = null, autoCheckInitialState: Boolean = true)` Initializes a new instance of the TestSettings class. ### Properties #### `autoCheckInitialState` - **Type**: Boolean - **Default**: `true` - **Description**: Set this to override the explicit initial state check for this test. #### `dispatcherOverride` - **Type**: `CoroutineDispatcher?` - **Default**: `null` - **Description**: Set this to override the Container's CoroutineDispatchers for this test. #### `exceptionHandlerOverride` - **Type**: `CoroutineExceptionHandler?` - **Default**: `null` - **Description**: Set this to override the Container's CoroutineExceptionHandlers for this test. ### Request Example ```json { "dispatcherOverride": null, "exceptionHandlerOverride": null, "autoCheckInitialState": true } ``` ### Response #### Success Response (200) This data class does not represent an API endpoint with a direct success response. It's a configuration object. #### Response Example ```json { "dispatcherOverride": null, "exceptionHandlerOverride": null, "autoCheckInitialState": true } ``` ``` -------------------------------- ### Reduce State (Kotlin) Source: https://orbit-mvi.org/dokka/orbit-core/org.orbitmvi.orbit.syntax/-syntax/index Illustrates the `reduce` function in Kotlin, which is responsible for updating the application state based on incoming events. It takes a reducer lambda that returns the new state. ```kotlin suspend fun reduce(reducer: IntentContext.() -> S) ``` -------------------------------- ### POST /websites/orbit-mvi/joinIntents Source: https://orbit-mvi.org/dokka/orbit-core/org.orbitmvi.orbit/-container/join-intents Joins all in-progress intents in the container. This function suspends until all intents have completed. ```APIDOC ## POST /websites/orbit-mvi/joinIntents ### Description Joins all in-progress intents in the container. This function suspends until all intents have completed. ### Method POST ### Endpoint /websites/orbit-mvi/joinIntents ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```json { "message": "No request body needed for this operation." } ``` ### Response #### Success Response (200) - **status** (string) - Indicates the successful completion of the operation. #### Response Example ```json { "status": "Intents joined successfully" } ``` ``` -------------------------------- ### AndroidIdlingResource Constructor Source: https://orbit-mvi.org/dokka/orbit-viewmodel/org.orbitmvi.orbit.viewmodel/-android-idling-resource/index Initializes a new instance of the AndroidIdlingResource class. This constructor does not require any parameters. ```kotlin class AndroidIdlingResource : IdlingResource(source) constructor() ``` -------------------------------- ### Syntax Source: https://orbit-mvi.org/dokka/orbit-core/org.orbitmvi.orbit.syntax/index Provides syntax for interacting with a `ContainerContext` in Orbit MVI. ```APIDOC ## Syntax ### Description Provides syntax for interacting with a `ContainerContext` in Orbit MVI, simplifying operations on the container's state and side effects. ### Type `class Syntax` ### Parameters - **containerContext** (ContainerContext) - The container context to operate on. ``` -------------------------------- ### RealContainer Constructor Source: https://orbit-mvi.org/dokka/orbit-core/org.orbitmvi.orbit.internal/-real-container/index Initializes a new instance of the RealContainer class. It requires an initial state, a parent CoroutineScope, and settings for the container. An optional subscribedCounterOverride can be provided. ```kotlin RealContainer( initialState: STATE, parentScope: CoroutineScope, settings: RealSettings, subscribedCounterOverride: SubscribedCounter? = null ) ``` -------------------------------- ### LazyCreateContainerDecorator Constructor Source: https://orbit-mvi.org/dokka/orbit-core/org.orbitmvi.orbit.internal/-lazy-create-container-decorator/-lazy-create-container-decorator Initializes the LazyCreateContainerDecorator with an actual container and a creation lambda. The `actual` parameter is the underlying container, and `onCreate` is a suspend function executed when the container is first needed, defining its initial state and side effects. ```kotlin constructor( actual: Container, onCreate: suspend ContainerContext.() -> Unit )(source) ``` -------------------------------- ### Launch Intent on ContainerHost - Kotlin Source: https://orbit-mvi.org/dokka/orbit-core/org.orbitmvi.orbit/-container-host/index An extension function for `ContainerHost` that builds and executes an intent on the container. This function returns a `Job` representing the launched coroutine. ```kotlin fun intent( registerIdling: Boolean = true, transformer: suspend Syntax.() -> Unit): Job ``` -------------------------------- ### ContainerContext Properties Source: https://orbit-mvi.org/dokka/orbit-core/org.orbitmvi.orbit.syntax/-container-context/index Details the properties available on the ContainerContext class. ```APIDOC ## ContainerContext Properties ### Description Provides access to the internal state and functionalities of the ContainerContext. ### Properties - **postSideEffect** (suspend (SE) -> Unit) - Function to post side effects. - **reduce** (suspend ((S) -> S) -> Unit) - Function to reduce the state. - **settings** (RealSettings) - The settings associated with the container. - **state** (S) - The current state of the container. - **stateFlow** (StateFlow) - A Kotlin Flow representing the state. - **subscribedCounter** (SubscribedCounter) - A counter for active subscriptions. ``` -------------------------------- ### SubStateSyntax Properties Source: https://orbit-mvi.org/dokka/orbit-core/org.orbitmvi.orbit.syntax/-sub-state-syntax/index Details the properties of the SubStateSyntax class, including the current state. ```APIDOC ## SubStateSyntax Properties ### Description Provides access to the current state within the Orbit-MVI execution. ### Method GET ### Endpoint N/A ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```json { "example": "Not applicable for property access" } ``` ### Response #### Success Response (200) - **state** (T) - The current state which can change throughout the execution of the orbit block. #### Response Example ```json { "state": "current_state_value" } ``` ``` -------------------------------- ### ContainerContext Properties (Kotlin) Source: https://orbit-mvi.org/dokka/orbit-core/org.orbitmvi.orbit.syntax/-container-context/index Lists the key properties of the ContainerContext, including how to post side effects, reduce state, access settings, retrieve the current state, observe state changes via StateFlow, and manage subscription counts. ```kotlin val postSideEffect: suspend (SE) -> Unit val reduce: suspend ((S) -> S) -> Unit val settings: RealSettings val state: S val stateFlow: StateFlow val subscribedCounter: SubscribedCounter ``` -------------------------------- ### Define Syntax for Orbit Container Operations (Kotlin) Source: https://orbit-mvi.org/dokka/orbit-core/org.orbitmvi.orbit.syntax/index Defines the Syntax class, the primary entry point for interacting with an Orbit MVI container's context. It holds a ContainerContext and provides methods for state manipulation and side effect posting. ```kotlin class Syntax( val containerContext: ContainerContext ) ``` -------------------------------- ### StateItem Constructor (Kotlin) Source: https://orbit-mvi.org/dokka/orbit-test/org.orbitmvi.orbit.test/-item/-state-item/index The primary constructor for the StateItem class, which initializes the StateItem with a given state value. This constructor is essential for creating instances of StateItem. ```kotlin constructor(value: STATE) ``` -------------------------------- ### RealSettings Constructor Source: https://orbit-mvi.org/dokka/orbit-core/org.orbitmvi.orbit/-real-settings/index The RealSettings constructor allows for the configuration of various settings related to side effects, idling resources, dispatchers, and exception handling within the Orbit MVI framework. ```APIDOC ## RealSettings Constructor ### Description Initializes RealSettings with configurable parameters for Orbit MVI. ### Method CONSTRUCTOR ### Endpoint N/A ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **sideEffectBufferSize** (Int) - Optional - The buffer size for side effects. Defaults to `Channel.BUFFERED`. - **idlingRegistry** (IdlingResource) - Optional - The idling resource to use. Defaults to `NoopIdlingResource()`. - **eventLoopDispatcher** (CoroutineDispatcher) - Optional - The dispatcher for the event loop. Defaults to `Dispatchers.Default`. - **intentLaunchingDispatcher** (CoroutineDispatcher) - Optional - The dispatcher for launching intents. Defaults to `Dispatchers.Unconfined`. - **exceptionHandler** (CoroutineExceptionHandler?) - Optional - The exception handler for coroutines. Defaults to `null`. - **repeatOnSubscribedStopTimeout** (Long) - Optional - The timeout for stopping repeat operations when unsubscribed. Defaults to `100`. ### Request Example ```kotlin val settings = RealSettings( sideEffectBufferSize = 10, eventLoopDispatcher = Dispatchers.IO, exceptionHandler = CoroutineExceptionHandler { _, throwable -> /* handle exception */ } ) ``` ### Response #### Success Response (200) N/A (This is a constructor) #### Response Example N/A ``` -------------------------------- ### Manually Run onCreate in Tests Source: https://orbit-mvi.org/Test If your Container uses an `onCreate` lambda, it must be run manually within the test block using `runOnCreate()`. This ensures that the `onCreate` logic is isolated and testable, especially if it contains intent calls. ```kotlin @Test fun exampleTest() = runTest { ExampleViewModel().test(this) { runOnCreate() containerHost.countToFour() } } ``` -------------------------------- ### Asserting Container States Source: https://orbit-mvi.org/Test Assert the state of your container using `expectState()` or `awaitState()`. `expectState()` allows for state verification using a lambda, while `awaitState()` returns the next state for direct comparison. All emitted states must be consumed to prevent test failures. ```kotlin @Test fun exampleTest() = runTest { ExampleViewModel().test(this) { containerHost.countToFour() expectState { copy(count = 1) } // alternatively assertEquals(State(count = 1), awaitState()) expectState { copy(count = 2) } expectState { copy(count = 3) } expectState { copy(count = 4) } } } ``` -------------------------------- ### Converting String to Subscription Value (Kotlin) Source: https://orbit-mvi.org/dokka/orbit-core/org.orbitmvi.orbit.internal.repeatonsubscription/-subscription/index Explains how to convert a string representation back into a Subscription enum constant. The 'valueOf' function requires an exact match to an enum constant's name. ```kotlin val subscriptionFromString: Subscription = Subscription.valueOf("Subscribed") ``` -------------------------------- ### Execute Intent with Transformer in Kotlin Source: https://orbit-mvi.org/dokka/orbit-core/org.orbitmvi.orbit/-container-host/intent Builds and executes an intent on a Container. It allows for optional registration of an idling resource and takes a transformer lambda to define the intent's logic. The function returns a Job representing the execution. ```kotlin open fun intent( registerIdling: Boolean = true, transformer: suspend Syntax.() -> Unit): Job(source) ``` -------------------------------- ### NoopIdlingResource Class Source: https://orbit-mvi.org/dokka/orbit-core/org.orbitmvi.orbit.idling/index NoopIdlingResource is a concrete implementation of IdlingResource that does nothing, useful as a default or placeholder. ```APIDOC ## NoopIdlingResource Class ### Description A no-operation implementation of the IdlingResource interface. It is always considered idle and does not track any resources. ### Method N/A (Class) ### Endpoint N/A (Class) ### Parameters N/A (Class) ### Request Example N/A (Class) ### Response N/A (Class) ``` -------------------------------- ### Initialize Container with Default State and Intent Lambda in Kotlin Source: https://orbit-mvi.org/Core Containers in Orbit MVI are typically created using factory functions, allowing for initial state configuration and an intent lambda to be invoked upon creation. This is useful for setting up initial observations or performing actions when the container is first instantiated. ```kotlin perform("Toast the current state") class Example : ContainerHost { override val container = container(ExampleState()) { // This block is an intent invoked when the container is first created reduce { ... } } } ``` -------------------------------- ### Launch Blocking Intent on ContainerHost - Kotlin Source: https://orbit-mvi.org/dokka/orbit-core/org.orbitmvi.orbit/-container-host/index An extension function for `ContainerHost` that builds and executes an intent on the container in a blocking manner. It does not dispatch the intent, allowing for immediate execution. ```kotlin fun ContainerHost.blockingIntent(registerIdling: Boolean = true, transformer: suspend Syntax.() -> Unit) ``` -------------------------------- ### ContainerContext Constructor (Kotlin) Source: https://orbit-mvi.org/dokka/orbit-core/org.orbitmvi.orbit.syntax/-container-context/index The primary constructor for the ContainerContext class. It initializes the context with essential components for state management and side-effect handling. ```kotlin constructor( settings: RealSettings, postSideEffect: suspend (SE) -> Unit, reduce: suspend ((S) -> S) -> Unit, subscribedCounter: SubscribedCounter, stateFlow: StateFlow ) ``` -------------------------------- ### LazyCreateContainerDecorator Constructor (Kotlin) Source: https://orbit-mvi.org/dokka/orbit-core/org.orbitmvi.orbit.internal/-lazy-create-container-decorator/index Initializes the LazyCreateContainerDecorator with an actual container and an onCreate lambda. The onCreate lambda is executed when the container is first needed, allowing for lazy initialization of the container's state and side effects. ```kotlin class LazyCreateContainerDecorator( val actual: Container, val onCreate: suspend ContainerContext.() -> Unit ) : ContainerDecorator ``` -------------------------------- ### Create Orbit MVI ViewModel in Kotlin Source: https://orbit-mvi.org/index This Kotlin code demonstrates how to create a ViewModel using Orbit MVI. It implements the `ContainerHost` interface and uses the `ViewModel.container` factory function to manage state and side effects. ```kotlin class CalculatorViewModel: ContainerHost, ViewModel() { // Include `orbit-viewmodel` for the factory function override val container = container(CalculatorState()) fun add(number: Int) = intent { postSideEffect(CalculatorSideEffect.Toast("Adding $number to ${state.total}!")) reduce { state.copy(total = state.total + number) } } } ``` -------------------------------- ### TestContainerDecorator Constructor Source: https://orbit-mvi.org/dokka/orbit-core/org.orbitmvi.orbit.internal/-test-container-decorator/index Initializes a new instance of the TestContainerDecorator class. It takes the original initial state and the actual container to be decorated as parameters. This constructor is primarily used for setting up the decorator for testing. ```kotlin constructor(originalInitialState: STATE, actual: Container) ``` -------------------------------- ### Create OrbitTestContext for Testing Source: https://orbit-mvi.org/dokka/orbit-test/org.orbitmvi.orbit.test/index The `OrbitTestContext` class provides a testing environment for Orbit MVI containers. It holds the `containerHost`, initial state, emissions, and test settings, enabling detailed test assertions. ```kotlin class OrbitTestContext>( val containerHost: CONTAINER_HOST, resolvedInitialState: STATE, emissions: ReceiveTurbine>, settings: TestSettings ) ``` -------------------------------- ### awaitItem Function Source: https://orbit-mvi.org/dokka/orbit-test/org.orbitmvi.orbit.test/-orbit-test-context/await-item Retrieves the next item from the source. This function suspends execution if no items are currently available. ```APIDOC ## awaitItem ### Description Return the next item received. This function will suspend if no items have been received. ### Method SUSPEND ### Endpoint N/A (This is a function call, not a REST endpoint) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```kotlin val nextItem = awaitItem() ``` ### Response #### Success Response - **Item** (Item) - The next item received from the source. #### Response Example ```json { "item": { "state": { ... }, "sideEffect": { ... } } } ``` ``` -------------------------------- ### withIdling Extension Function Source: https://orbit-mvi.org/dokka/orbit-core/org.orbitmvi.orbit.syntax/-container-context/index Executes a block of code while managing idling state, optionally registering it. ```APIDOC ## withIdling Extension Function ### Description Executes a given block of code while ensuring proper idling state management. This function can optionally register the idling state. ### Method Extension Function ### Endpoint N/A (Extension function) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **operator** (O) - The operator associated with the idling operation. - **block** (suspend O.() -> T) - The suspend function block to execute. - **registerIdling** (Boolean) - Flag to indicate whether to register the idling state. - **block** (suspend ContainerContext.() -> Unit) - The suspend function block to execute. ### Request Example ```kotlin // Example 1: With operator val result = containerContext.withIdling(someOperator) { // perform operation someResult } // Example 2: With registerIdling flag containerContext.withIdling(registerIdling = true) { // perform operation } ``` ### Response #### Success Response (200) - **T** (T) - The result of the executed block (if applicable). - **Unit** - If the block returns Unit. #### Response Example ```json { "message": "Operation completed with idling management." } ``` ``` -------------------------------- ### Create Orbit MVI Container (Kotlin) Source: https://orbit-mvi.org/dokka/orbit-core/org.orbitmvi.orbit/container The `container` function helps create a concrete container in a standard way for Orbit MVI. It takes an initial state, optional build settings, and an onCreate lambda to execute when the container is created. The onCreate lambda is executed lazily by default. ```kotlin fun CoroutineScope.container( initialState: STATE, buildSettings: SettingsBuilder.() -> Unit = {}, onCreate: suspend Syntax.() -> Unit? = null): Container(source) ``` -------------------------------- ### Infinite Flow Middleware with Delay (Kotlin) Source: https://orbit-mvi.org/Test Defines an Orbit MVI middleware that emits states indefinitely with a delay. This is used to demonstrate testing scenarios with and without delay skipping. ```kotlin class InfiniteFlowMiddleware : ContainerHost, Nothing> { override val container: Container, Nothing> = someScope.container(listOf(42)) fun incrementForever() = intent { while (true) { delay(30_000) reduce { state + (state.last() + 1) } } } } ``` -------------------------------- ### ContainerHost Interface Source: https://orbit-mvi.org/dokka/orbit-core/org.orbitmvi.orbit/-container-host The ContainerHost interface is applied to components that act as Orbit container hosts. It provides access to the Orbit container and functions for dispatching intents. ```APIDOC ## ContainerHost Interface ### Description Apply this interface to anything you want to become an Orbit container host. Typically this will be an Android ViewModel but it can be applied to simple presenters etc. ### Members #### Properties - **container** (Container) - The Orbit Container instance. #### Functions - **blockingIntent**(registerIdling: Boolean = true, transformer: suspend Syntax.() -> Unit): Job - Build and execute an intent on Container in a blocking manner, without dispatching. - **intent**(registerIdling: Boolean = true, transformer: suspend Syntax.() -> Unit): Job - Build and execute an intent on Container. - **subIntent**(transformer: suspend Syntax.() -> Unit) - Used for parallel decomposition or subdivision of a larger intent into smaller parts. ``` -------------------------------- ### Run On State (Kotlin) Source: https://orbit-mvi.org/dokka/orbit-core/org.orbitmvi.orbit.syntax/-syntax/index Showcases the `runOn` inline suspend function in Kotlin, designed for type-safe handling of sealed class states. It allows executing a block of code conditionally based on the current state, with an optional predicate. ```kotlin inline suspend fun runOn( crossinline predicate: (T) -> Boolean = { true }, crossinline block: suspend SubStateSyntax.() -> Unit) ``` -------------------------------- ### Syntax Class Definition (Kotlin) Source: https://orbit-mvi.org/dokka/orbit-core/org.orbitmvi.orbit.syntax/-syntax/index Defines the Syntax class in Kotlin, a core component of Orbit MVI for managing state and side effects. It includes a constructor and properties for context and state. ```kotlin class Syntax(val containerContext: ContainerContext)(source) constructor(containerContext: ContainerContext) val containerContext: ContainerContext val state: S ```