Giter VIP home page Giter VIP logo

bansa's Introduction

Bansa

This is my take on Redux, the state container for JavaScript apps. It's oriented toward developers who like building React-style apps and Kotlin!

Why the name Bansa? Because it means "Nation" in Filipino. And nations are "state containers." Get it!? Oh ho ho ho. Continue on for more, dear reader.

Get it!

// First, add JitPack to your repositories
repositories {
	...
	maven { url "https://jitpack.io" }
}

// Base package. Everything else is built upon it!
compile 'com.github.brianegan.bansa:bansa:1.0.0-beta'

// If you'd like a more functional interface in Kotlin, go ahead and use the Kotlin Extensions.
compile 'com.github.brianegan.bansa:bansaKotlin:1.0.0-beta'

// Time Travel Dev Tools! Highly recommended you only use them
// for development, as the store takes up more memory. Note: You can use
// the provided UI, or write your own.
debugCompile 'com.github.brianegan.bansa:bansaDevTools:1.0.0-beta'
debugCompile 'com.github.brianegan.bansa:bansaDevToolsUi:1.0.0-beta'

What's the goal?

"State Container" is pretty vague. So let me explain what I'm trying to accomplish with this little project: An easier way to write Android UIs & Apps. Perhaps an easy way to start would be a concrete analogy.

Think about List and RecyclerViews on Android. At a high level, you just give them some data and tell them how to render that data. When the data updates, you call notifyDataSetChanged to inform the View and it redraws everything for ya. Nice and simple. And heck, with RecyclerView, it'll even perform some pretty impressive animations with just a couple lines of code!

That's what I'm going for with this project: I want a simple way to declare the way my interface should look, and when the data changes, everything should re-render for me!

So where does Bansa fit into that picture, one might ask? It doesn't say anything on the box about making my life easier as a UI developer!?

Bansa doesn't handle the UI magic. That's left to other tools, namely Anvil. Bansa is responsible for holding, or "containing," the state of your application, and informing the UI layer (or database layer, or logging layer, etc) about updates to the state of the application.

The examples in this project simply show one person's vision for how we could think about Android App development, and whether we could make it easier and more fun.

Using it

We'll demonstrate using a simple counter example!

Define what your state should look like

All we need for a simple counter example is the value of one counter. In one delicate line with Kotlin:

data class ApplicationState(val counter: Int = 0)

Define the types of actions of your application

Actions are payloads of information that send data from your application to your state container, which we'll call the store from here on out. They are used to determine what actions your store should respond to. You send them from your application to a store with the store.dispatch(ACTION) method.

So here are the three actions we need for our counter app:

object INIT : Action
object INCREMENT : Action
object DECREMENT : Action

Update the state with Reducers

Actions describe the fact that something happened, but don’t specify how the application’s state changes in response. This is the job of a reducer.

Let's see some code and we'll chat about it afterwards:

val reducer = Reducer<ApplicationState> { state, action ->
    when (action) {
        is INIT -> ApplicationState()
        is INCREMENT -> state.copy(counter = state.counter.plus(1))
        is DECREMENT -> state.copy(counter = state.counter.minus(1))
        else -> state
    }
}

So what's happening here? A reducer is a function that takes two arguments: the current state of the application, and the action that was fired. It returns an updated version of the state.

In this example, when the INIT action is fired, we want to initialize the state of our application. Therefore, we return a new instance.

When the INCREMENT action is fired, we want to simply increase the counter by 1.

If DECREMENT is fired, we'll need to decrease the counter by 1.

And that's all there is to it: We're simply describing how the state should change in response to an action.

Create a new store (this is your state container)

Now that we've gotten everything setup, we can create our state container!

val counterStore = BaseStore(ApplicationState(), reducer);

And that's it! Now you've got a store. Woohoo! So what now?

Dispatch (Fire / Trigger) an action

The following code will dispatch an action that travels first through any middleware (we'll chat about those later), then through the reducers, generally producing a state change.

counterStore.dispatch(INCREMENT)

Get the current state of the store

Say you want to know what the current state of the app is. That's simple:

counterStore.getState() // After the INCREMENT, state is now (counter = 1)

And this is where the magic begins: Subscribe to updates!

counterStore.subscribe({
    textView.setText(store.getState())
})

ZOMG MY TEXT JUST UPDATED DUE TO A STATE CHANGE!!!

Stay with me!

I know what you're saying: "Bri, I've seen all this before. It's called an EVENT BUS." And you know what? You're pretty much right. This isn't anything radical, it's just gluing some pieces together in a different way. But just think about how we can use this pattern to simplify our UIs.

Hooking it up to Anvil

Ok, so now we have to chat about Anvil. It's a simple way to write UIs in Java & Kotlin, and it might be a bit different than what you're used to. With Anvil, you simply describe your UI in Java / Kotlin code (not XML -- give it a few minutes, I think you'll fall in love), update the state, and call Anvil.render(). Then everything just updates! We've done it! We've achieved the goal set out in the opening paragraphs!!!

So here's an example view. It's job is to create a linearLayout with three child views: A text view to display the current count, an plus button, and a minus button.

When someone clicks on the plus button, we want to dispatch an INCREMENT action. When someone clicks the minus button, we want to dispatch a DECREMENT action.

linearLayout {
    size(FILL, WRAP)
    orientation(LinearLayout.VERTICAL)

    textView {
        text("Counts: ${store.state.counter.toString()}") // The counter from our state model!
    }

    button {
        size(FILL, WRAP)
        padding(dip(10))
        text("+")
        onClick(store.dispatch(INCREMENT))
    }

    button {
        size(FILL, WRAP)
        padding(dip(5))
        text("-")
        onClick(store.dispatch(DECREMENT))
    }
}

And now, we hook anvil and Bansa up together:

counterStore.subscribe({
    Anvil.render()
})

That's right: When a user clicks "+", the increment action will be fired, the reducer will update the state, and our UI will auto-render with the new info. WHAAAAAAAAAAT.

Dev Tools

Maybe one of the cooler bonuses about this pattern is that it happens to lend itself well to time-travel style Dev tools! What are time travel dev tools you say? What if, for every action you take in an application, you could replay what happened? Then you could step forward and backward through that series of actions to see the steps along the way. You can totally do that with Bansa!

More documentation needs to be written about implementing the Time Travel Dev tools, but for now, please see the Counter example as a reference implementation! It should be possible to get the Dev Tools up and running with only a small amount of code.

Dev Tools Screenshot

Screenshot of the Dev Tools in action

Examples

There are a progression of examples that can be found in the "Examples" folder. If you're interested in progressing through them, the suggested order is:

  1. Counter
  2. Counter pair
  3. List of counters
  4. List of counters variant
  5. Random gif
  6. List of trending gifs
  7. Todo List

More docs -- public shameful note for Brian

Write sections for:

  • Async Actions
  • Middleware
  • Combining reducers
  • Breaking down apps into smaller parts

Things to think about

  • How views should asynchronously request / remove data from the store upon instantiation and disposal if it's safe.
  • What is the role of the database? Store actions? Store models?
  • Could views describe their data requirements as queries, similar to Falcor or GraphQL?

Technical Goals

If you're thinking of writing your own version of Redux in Java: I'd say, go for it! This libray has benefitted tremendously from the various versions that have been written thus far, and the current version is an attempt to synthesize the best parts of each implementation. When evaluating the various libs, I came up with a bucket list for what this library should accomplish for a 1.0 release:

  • Idiomatic Java and Kotlin usage.
  • Low method count
  • Easy to pick up, even if you come from a less functional background.
  • Support for all basic Redux concepts in the smallest possible package. This includes the Store, Middleware, Reducers, and Subscribers/Subscriptions, and combining Reducers.
  • Dev Tools that allow for Time Travel debugging
  • Interface that allows for sharable middleware & reducers (such as Logging middelware, or Undo/Redo reducer helpers)
  • Well tested

The tech setup

If you like Buzzwords, then boy howdy, have you found yourself the right repo.

Bansa itself has one important dependency, RxJava, and is written in Kotlin.

The examples use:

  • Kotlin (yay! it's so lovely.)
  • Anvil for UI
  • RxJava for Observables
  • OkHttp for, uh, http
  • Moshi for Json parsing
  • Picasso for image loading
  • JUnit for Unit Testing
  • AssertJ to make dem assertions all fluent like

Inspiration

I'd also like to add that this library is a complete , these ideas aren't new in any way. Credit has to be given to the following projects, listed in autobiographical order.

  • React
  • Om
  • ClojureScript
  • Elm
  • Redux
  • CycleJs
  • redux-java - by my coworker and friend, Guillaume Lung
  • re-frame

bansa's People

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

bansa's Issues

Remove Spek

Spek was experimental, but I don't find it's as powerful or useful as reliable ol' jUnit. Let's remove it in favor of jUnit tests for all examples.

Jitpack in README

You've forgotten to add maven { url "https://jitpack.io" } to "How to install".

Question: Is this still maintained?

This is awesome. Wondering if this is still maintained? It would be a shame if not. There's no other redux implementation in java as good as this.

should bansaDevToolsUi be an "aar" instead of jar ?

Thank you for creating this useful library !

bansaDevToolsUi contains a res folder with an layout file
for the resource merger to work shouldn't this library be an aar bundle instead of an jar bundle ?

Manage global Store in an Android application

Hi,

I am currently learning to implement a small Android app with this library, but I am unsure where you would put the Store. Should there really be an application wide store Singleton and how would I handle orientation changes or the Android system killing the process and saving/restoring the state? Or is it better to put the store inside the ViewModel of the Android Architecture Components?

Thanks for your input!

Explore Component Based Architecture w/ LifeCycle

Goals:

  • Pass data down from one component to the next (Unidirectional data flow, ala React)
  • Components have access to the activity lifecycle (ActivityLightCycle from LightCycle as a possible interface)
  • Components have the concept of a render type of function. view Might make more sense as it means we could use the Anvil renderable interface.
  • Usable with / in? Adapters
  • Render function that takes in a Props model
  • Local ViewModel state that is updated by render, which combines local state and passed in props
  • "Mount" component

Gradle install instructions

Is this up on Maven? I can't seem to find it. I'm guessing I have to download and link to the project manually for now?

Better Documentation

Follow the advice in the readme and update the docs to include a more step-by-step guide

InjektionException: No registered instance or factory for type com.brianegan.bansa.Store

Hi,

I just wanted to try your Bansa counter example (by the way, I have to chuckle every time I misread this as "Bansa counterexample") and it crashed with the following exception:

java.lang.RuntimeException: Unable to instantiate application com.brianegan.bansa.counter.Application: uy.kohesive.injekt.api.InjektionException: No registered instance or factory for type com.brianegan.bansa.Store<com.brianegan.bansa.counter.ApplicationState, com.brianegan.bansa.Action>
    at android.app.LoadedApk.makeApplication(LoadedApk.java:526)
    at android.app.ActivityThread.handleBindApplication(ActivityThread.java:4390)
    at android.app.ActivityThread.access$1500(ActivityThread.java:139)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1260)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:136)
    at android.app.ActivityThread.main(ActivityThread.java:5105)
    at java.lang.reflect.Method.invokeNative(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:515)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:792)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:608)
    at dalvik.system.NativeStart.main(Native Method)
Caused by: uy.kohesive.injekt.api.InjektionException: No registered instance or factory for type com.brianegan.bansa.Store<com.brianegan.bansa.counter.ApplicationState, com.brianegan.bansa.Action>
    at uy.kohesive.injekt.registry.default.DefaultRegistrar.getInstance(DefaultRegistrar.kt:99)
    at uy.kohesive.injekt.api.InjektScope.getInstance(Scope.kt)
    at com.brianegan.bansa.counter.Application.<init>(Application.kt:30)
    at java.lang.Class.newInstanceImpl(Native Method)
    at java.lang.Class.newInstance(Class.java:1208)
    at android.app.Instrumentation.newApplication(Instrumentation.java:990)
    at android.app.Instrumentation.newApplication(Instrumentation.java:975)
    at android.app.LoadedApk.makeApplication(LoadedApk.java:521)
    ... 11 more

I haven't done much Kotlin and haven't used Injekt at all - could you tell me what I am doing wrong?

Kotlin

Thank you so much for your work on this. It is really nice library. I am a big fan of Redux.

  1. Can you share why you decide to move implementation away from Kotlin -> Java?
  2. Do you have any support for StoreEnhancer ?

Subscribe to substate?

I'm working on fairly complexe application, and I'm splitting my AppState into multiple substate, so I have multiple reducers and states. It works fine, but is there a way to subscribe to change only happening to a specific part of my state?

To get you an idea here is my AppState

class AppState {
    var userState = UserState()
}

and my UserState

class UserState {
    var currentUser: String? = null
    var users = mutableMapOf<String, User>()
}

and my AppReducer

class AppReducer: Reducer<AppState> {
    val userReducer = UserReducer()

    override fun reduce(state: AppState, action: Action?): AppState {
        userReducer.reduce(state.userState, action)
        return state
    }
}

So when I subscribe, I would want to do something like this:

store.subscribe { state.userState ->
  Log.d("State change", state.userState.currentUser)
}

is that something possible or planned?

Thanks!

Is it safe to call dispatch from multiple threads?

Hello, thank you for introducing Redux to Android world.

I'm using bansa with Anvil and I think they are a very good match. But I noticed one thing, if we call BaseStore.dispatch() from multiple thread, it's possible to get inconsistent state within one dispatch cycle, since we can't pass the new state to Anvil.render(). We could only use BaseStore.getState() in each view.

I noticed that you use locks in this line and getState(). But they both lock on different objects. synchronized(this) locks on Middleware instance while public synchronized S getState() locks on BaseStore instance.

But I think although we use locks, there is still a chance for inconsistent state since dispatch and getState will not be called in one block.

Do you think we should only call dispatch in one thread? Maybe using a single background thread to do it?

I'll be grateful to hear your thoughts about this. Thank you very much.

If I feel like I want to dispatch from my Reducer - what is the correct thing to do instead?

Hi Brian,

I keep running into situations where my first impulse would be to dispatch a new Action to my store from within my Reducer. But since I don't even have a reference to the store there and since dispatching from the reducer is very much discouraged in Redux I suppose that's not the way to go in Bansa either. Still I can't figure out what to do instead.

For example: I try to load a list of images from my API but the request fails because I am not logged in and so the login form is displayed instead. The login request succeeds and LOGIN_SUCCESS is dispatched. Since I have also stored (something like) retryImageListRequest = true in my state I could now dispatch another LOAD_IMAGE_LIST and load the images in the appropriate Middleware. Except that would mean I would dispatch an Action from within my Reducer.

Unfortunately, I am not only new to Bansa but to similar frameworks as well (I've only done some Elm, and that was only with synchronous computations), so I can't make much sense of articles like this one:

Now you know that this is frowned on. You know that if you have enough information to dispatch an action after the reducer does its thing, then it is a mathematical certainty that you can do what you want without dispatching another action.

I would be very grateful for any suggestions!

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.