allen218 / orbit-mvi

A simple MVI framework for Kotlin Multiplatform and Android

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Orbit for Kotlin and Android

CI status codecov Download License

Logo

slack logo Join us at the Kotlinlang slack!

If you do not yet have an account with the Kotlinlang slack workspace, sign up here.

This library was originally developed at Babylon Health. However, as its development over there ceased, further development has been moved to this project maintained by the original authors.

Documentation

Overview

Orbit is a simple scaffolding you can build a Redux/MVI-like architecture around.

  • Easy to use, type-safe, extensible API
  • Built on top of coroutines
  • Compatible with RxJava, LiveData etc. through coroutine wrappers
  • ViewModel support, along with SavedState!
  • Unit test framework designed in step with the framework
  • Built-in espresso idling resource support

And more!...

Getting started in three simple steps

implementation("org.orbit-mvi:orbit-viewmodel:<latest-version>")

Download

Define the contract

First, we need to define its state and declared side effects.

data class CalculatorState(
    val total: Int = 0
)

sealed class CalculatorSideEffect {
    data class Toast(val text: String) : CalculatorSideEffect()
}

The only requirement here is that the objects are comparable. We also recommend they be immutable. Therefore we suggest using a mix of data classes, sealed classes and objects.

Create the ViewModel

Using the core Orbit functionality, we can create a simple, functional ViewModel.

  1. Implement the ContainerHost interface
  2. Override the container field and use the ViewModel.container factory function to build an Orbit Container in your ContainerHost
class CalculatorViewModel: ContainerHost<CalculatorState, CalculatorSideEffect>, ViewModel() {

    // Include `orbit-viewmodel` for the factory function
    override val container = container<CalculatorState, CalculatorSideEffect>(CalculatorState())

    fun add(number: Int) = intent {
        postSideEffect(CalculatorSideEffect.Toast("Adding $number to ${state.total}!"))

        reduce {
            state.copy(total = state.total + number)
        }
    }
}

We have used an Android ViewModel as the most common example, but there is no requirement to do so. You can host an Orbit Container in a simple class if you wish. This makes it possible to use in simple Kotlin projects as well as lifecycle independent services.

Connect to the ViewModel in your Activity or Fragment

Now we need to wire up the ViewModel to our UI. We expose coroutine Flows through which one can conveniently subscribe to updates. Alternatively you can convert these to your preferred type using externally provided extension methods e.g. asLiveData or asObservable.

class CalculatorActivity: AppCompatActivity() {

    // Example of injection using koin, your DI system might differ
    private val viewModel by viewModel<CalculatorViewModel>()

    override fun onCreate(savedState: Bundle?) {
        ...
        addButton.setOnClickListener { viewModel.add(1234) }

        lifecycleScope.launchWhenCreated {
            viewModel.container.stateFlow.collect { render(it) }
        }
        lifecycleScope.launch {
            viewModel.container.sideEffectFlow
                .flowWithLifecycle(lifecycle, Lifecycle.State.STARTED)
                .collect { handleSideEffect(it) }
        }
    }

    private fun render(state: CalculatorState) {
        ...
    }

    private fun handleSideEffect(sideEffect: CalculatorSideEffect) {
        when (sideEffect) {
            is CalculatorSideEffect.Toast -> toast(sideEffect.text)
        }
    }
}

Syntax

class MyViewModel: ContainerHost<MyState, MySideEffect>, ViewModel() {

    override val container = container<MyState, MySideEffect>(MyState())

    fun loadDataForId(id: Int) = intent {
        postSideEffect(MySideEffect.Toast("Loading data for $id!"))

        val result = repository.loadData(id)

        reduce {
            state.copy(data = result)
        }
    }
}

Modules

Orbit is a modular framework. The Core module provides basic Orbit functionality with additional features provided through optional modules.

Orbit supports using various async/stream frameworks at the same time so it is perfect for legacy codebases. For example, it can support both RxJava and coroutines if you are in the process of migrating from one to the other.

At the very least you will need the orbit-core module to get started, alternatively include one of the other modules which already include orbit-core.

implementation("org.orbit-mvi:orbit-core:<latest-version>")
implementation("org.orbit-mvi:orbit-viewmodel:<latest-version>")

testImplementation("org.orbit-mvi:orbit-test:<latest-version>")

Download

Contributing

Please read CONTRIBUTING.md for details on our code of conduct, and the process for submitting pull requests to us.

Versioning

We use SemVer for versioning. For the versions available, see the tags on this repository.

License

License

This project is licensed under the Apache License, Version 2.0 - see the LICENSE.md file for details

About

A simple MVI framework for Kotlin Multiplatform and Android

License:Apache License 2.0


Languages

Language:Kotlin 100.0%