Git Product home page Git Product logo

rx-property-android's Introduction

RxProperty Android

Bindable and observable property for Android Data Binding

This library is an Android port of ReactiveProperty.

Demo

Download

repositories {
    maven { url "https://jitpack.io" }
}

dependencies {
    compile 'com.github.k-kagurazaka.rx-property-android:rx-property:4.0.0'

    // If you want to use Kotlin syntax
    compile 'com.github.k-kagurazaka.rx-property-android:rx-property-kotlin:4.0.0'
}

Basics Usage

First, declare a view model class with RxProperty and RxCommand.

RxProperty represents a variable of a view state and RxCommand represents a command of "Command Pattern", which is abstraction of user manipulation.

public class ViewModel {
  public final RxProperty<String> input;
  public final ReadOnlyRxProperty<String> output;
  public final RxCommand<NoParameter> command;

  public JavaViewModel() {
    input = new RxProperty<>("")
        .setValidator(it -> TextUtils.isEmpty(it) ? "Text must not be empty!" : null);

    output = new ReadOnlyRxProperty<>(input.map(String::toUpperCase));

    command = new RxCommand<>(input.onHasErrorsChanged().map(it -> !it));
    command.subscribe(it -> { input.set("clicked!"); });
  }

Next, write a layout XML to bind the view model. Both one-way (by @{}) and two-way (by @={}) binding are supported.

<layout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">
    <data>
        <variable name="viewModel" type="ViewModel" />
    </data>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

        <EditText
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:inputType="text"
            android:text="@={viewModel.input.value}" />

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="@{viewModel.output.value}" />

        <Button
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Is not empty?"
            app:rxCommandOnClick="@{viewModel.command}" />
    </LinearLayout>
</layout>

Finally, execute data binding in your activity.

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    ActivityMainBinding binding = DataBindingUtil.setContentView(this, R.layout.activity_main);
    binding.setViewModel(new ViewModel());
  }

You are done!

Important Note: These snippets skips resource management/error handling for simplicity.

Validation

RxProperty provides validation. To use this feature, simply call setValidator method after RxProperty created.

public final RxProperty<String> input = new RxProperty<>("")
        .setValidator(it -> TextUtils.isEmpty(it) ? "Text must not be empty!" : null);

RxProperty also supports error notification with TextInputLayout.

<android.support.design.widget.TextInputLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    app:error="@{viewModel.input.error}"
    app:errorEnabled="@{viewModel.input.hasError}">

    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:inputType="text"
        android:text="@={viewModel.input.value}"/>
</android.support.design.widget.TextInputLayout>

RxCommand with Trigger

By default, the library provides the only View#onClick binder for RxCommand. If you want to bind RxCommand to others view events, implement BindingAdapter for your desired events or use trigger binding.

RxCommand can be kicked by Observable by the bindTrigger method. RxBinding is match for the use.

// When the menu whose id is R.id.some_menu is selecetd, someMenuCommand executes
viewModel.someMenuCommand.bindTrigger(RxMenuItem.clicks(menu.findItem(R.id.some_menu)));

Create from android.databinding.Observable

If you already have a android.databinding.Observable based view model, you can use a converter from the view model into io.reactivex.Observable. The library provides a feature to convert from io.reactivex.Observable to RxProperty, so you easily create RxProperty from the view model.

class Person extends BaseObservable { ... }

Person person = new Person("John", "Smith");
Observable<String> firstNameChanged = Observe.propertyOf(person, BR.firstName, it -> it.getFirstName());
RxProperty<String> firstName = new RxProperty<>(firstNameChanged, person.getFirstName());

Kotlin Support

There are some useful extension methods in `rx-property-kotlin'.

class Person : BaseObservable { ... }

class ViewModel {
    val input = RxProperty("")
            .setValidator { if (TextUtils.isEmpty(it)) "Text must not be empty!" else null }

    val output = input.map(String::toUpperCase).toReadOnlyRxProperty()

    val command = input.onHasErrorsChanged()
            .map { !it }
            .toRxCommand<NoParameter>()

    val person = Person("John", "Smith")
    val firstName = person.observeProperty(BR.firstName) { it.firstName }
            .toRxProperty()

    init {
        command.subscribe { input.set("clicked!") }
    }
}

License

The MIT License (MIT)

Copyright (c) 2016 Keita Kagurazaka

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

rx-property-android's People

Contributors

k-kagurazaka avatar

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

Watchers

 avatar  avatar  avatar  avatar  avatar

rx-property-android's Issues

Sample fix

Sample doesn't use RxBinding now.
Use it to bind to RxCommand.

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.