Cinder


Source link: https://github.com/akiraspeirs/Cinder

Cinder

Cinder helps you write concise and declarative code with Android’s data binding Observable classes.

It doesn't need any setup and you can start using it with your existing Observable code.

The library is in version zero so its interface and implementation might change or be unstable.

What it does:

//You can write this: Class ReceiptItem{

  public final ObservableInt quantity = new ObservableInt();

  public final ObservableInt price = new ObservableInt();

  public final ObservableInt total = Cinder.computeInt(()-> quantity.get() * price.get(),

quantity, price);
 
}
  //Instead of something this: Class ReceiptItem{

  public final ObservableInt quantity = new ObservableInt();

  public final ObservableInt price = new ObservableInt();

  public final ObservableInt total = new ObservableInt();

private OnPropertyChangedCallback totalObserver = new OnPropertyChangedCallback() {

@Override

public void onPropertyChanged(Observable sender, int propertyId) {

 total.set(quantity.get() * price.get());

}

  
}
;
public ReceiptItem(){

quantity.addOnPropertyChangedCallback(totalObserver);

price.addOnPropertyChangedCallback(totalObserver);
  
}
 
}

Other Examples:

//Observe properties of array elements Class Receipt{

  public final ObservableArrayList<RecepitItem> items = new ObservableArrayList<>();

//Recalculates when items are added/removed or if their totals change.
  public final ObservableInt total = Cinder.computeInt(()->{

int total = 0;

for (RecepitItem item: items){

 total += item.total.get();

}

return total;
  
}
, Cinder.observable(items, RecepitItem.class, "total"));
 
}
  //You can also convert to and from RxJava Observables:
  Observable<Long> rxLong = RxCinder.convert(observableLong);

  ObservableLong observableLong = RxCinder.convertLong(rxLong);

For more examples see the cinderexample app, the documentation below, or the test suite.

Installing:

You can install Cinder and RxCinder using JitPack.io:

 repositories {

maven {

 url "https://jitpack.io"

}

  
}
 dependencies {

compile 'com.github.akiraspeirs:cinder-rx:0.3.2'
  
}

Strongly recommended to be used with Retrolambda

Reference:

ObservableEvent class:

//A BaseObservable subclass that holds no data. Calling .fire() triggers notifyChange(). ObservableEvent addFruit = new ObservableEvent();
  //XML: <Button  android:onClick="@{
()->fruitshop.addFruit.fire()
}
" />

Basic compute methods:

// Returns an ObservableInt subclass that is updated with the return value of the computeCallback // whenever any of the specified observables call notifyChange. public static CinderInt computeInt(OnComputeIntCallback computeCallback,

BaseObservable... observables);
  // Example: ObservableInt fruitCount = Cinder.computeInt(()->
  appleCount.get() + bananaCount.get() + orangeCount.get(),
  appleCount, bananaCount, orangeCount);

List and Map compute methods:

// Returns an ObservableArrayList subclass that can be updated via the list argument of the // computeCallback whenever any of the specified observables call notifyChange. public static <T> CinderArrayList<T> computeArrayList(OnComputeArrayListCallback<T> computeCallback,

BaseObservable... observables);
  // Example: ObservableArrayList<String> fruits = Cinder.<String>computeArrayList((list)->
  list.add(newFruitName.get()), addFruitEvent);

Observable list and map conversion methods:

// Makes an Observable that notifies changes whenever the list is mutated. This is useful in // conjection with observe and compute methods. public static CinderComputable observable(ObservableList list);
  // Example: ObservableInt length = Cinder.ComputeInt(()->list.get().length(), Cinder.observable(list));
  // Makes an Observable that notifies changes whenever the list is mutated or an element's Observable // field changes. public static CinderComputable observable(ObservableList list, Class c, String... fields);
  // Example: ObservableInt tastiness = Cinder.ComputeInt(()->
  getAverageTastiness(list),
  Cinder.observable(list, Fruit.class, "tastiness"));

Basic observe methods:

// When you need to just observe. public static CinderObservable observe(OnChangeCallback onChangeCallback,

BaseObservable... observables);
  // Example: Observable observable = Cinder.observe(()->{

fruitService.recordTotalFruitCount(appleCount.get() + bananaCount.get();

  
}
, appleCount, bananaCount);

List and Map observe methods:

// Runs onChangeCallback whenever the collection is mutated, or when any specified BaseObservable // fields of the list elements calls notifyChange public static <T> CinderObservable observe(OnChangeCallback onChangeCallback,

ObservableList<T> list, Class c, String... fields);
  // Example: Observable fruitObserver = Cinder.observe(()->{

fruitService.uploadAllFruits(list);

  
}
, list, Fruit.class, "name", "tastiness"));
  // Runs onChangeCallback whenever the collection is mutated. public static <T> CinderObservable observe(OnChangeCallback onChangeCallback,

ObservableList<T> list);
  // Example: Observable fruitObserver = Cinder.observe(()->fruitService.uploadAllFruits(list), list);

Operators:

//Operators can be used to filter and control how callbacks are triggered. Example: final public ObservableArrayList<String> fruits = Cinder.<String>computeArrayList((list)->

 list.add(newFruit.get()),

addFruit)

.filter(()->newFruit.get().length() > 0) //Don't process fruits without a name.

.skip(5) //Don't process the first five times a fruit is added

.onUiThread();
 //Run the callback on the UI thread.  //Triggers the callback once and then stops. public Observable once();
  //Trigers the callback the specified amount of times then stops. public Observable take(int take);
  //Skips triggering the callback the specified amount of times. public Observable skip(int skip);
  //Only triggers the callback if the filter returns true. public Observable filter(CinderObservable.Filter filter);
  //Triggers while the filter is true then stops. public Observable takeWhile(CinderObservable.Filter filter);
  //Skips triggering while the filter is true. public Observable skipWhile(CinderObservable.Filter filter);
  //Runs the callback on the UI thread. public Observable onUiThread();
  //Sets a default value for the computed property. public ObservableInt withDefault(int defaultValue);
  //Runs the callback once immediately. public Observable immediate();
  //Debounces the callback by the specified milliseconds. public Observable debounce(long debounce);

Operator precedence:

filter > skipFilter > takeFilter > skip > take

For example, if you call filter(()->check()).skip(3).take(2), it will always check the filter first, then skip 3 and then take 2.

Stopping:

// Stops the callback triggering. Stopping removes all observers used to run the callback. It // doesn't remove callbacks observing the obervable. public void stop();

Notes

Memory management:

  • All callbacks and objects generated by Cinder will clean themselves up automatically, so long as their owning objects are not leaking.
  • A Cinder variable's callbacks cannot be garbage collected until its owner and all Observables it's computed from can be garbage collected.
  • The owner of a Cinder callback cannot be garbage collected if any of its Cinder callbacks cannot be garbage collected.

Thread safety:

  • debounce() will run the callback in a Timer thread, unless used with onUiThread(). Make sure your debounced callbacks are threadsafe.

Roadmap

  • Add more operators.

License

MIT License

Copyright (c) 2016 akiraspeirs

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.

Resources

Easily set up phone authentication leveraging on different auth platform (Firebase, Sinch) of your choice.

An example project / library of sticky recyclerview.

This is contains below components:

  • StickyRecyclerAdapter
  • StaticLinearLayoutManager
  • StickyVerticalLayoutManager
  • MultiCheckableStickyAdapter

A Simple View Pager Indicator with animations.

Nice and simple DSL for Espresso in Kotlin.

A simple cool animated edit text with a expandable animation.

Group of useful kotlin extension I made for application development in kotlin language which helps in day to day life of android developers!

Topics


2D Engines   3D Engines   9-Patch   Action Bars   Activities   ADB   Advertisements   Analytics   Animations   ANR   AOP   API   APK   APT   Architecture   Audio   Autocomplete   Background Processing   Backward Compatibility   Badges   Bar Codes   Benchmarking   Bitmaps   Bluetooth   Blur Effects   Bread Crumbs   BRMS   Browser Extensions   Build Systems   Bundles   Buttons   Caching   Camera   Canvas   Cards   Carousels   Changelog   Checkboxes   Cloud Storages   Color Analysis   Color Pickers   Colors   Comet/Push   Compass Sensors   Conferences   Content Providers   Continuous Integration   Crash Reports   Credit Cards   Credits   CSV   Curl/Flip   Data Binding   Data Generators   Data Structures   Database   Database Browsers   Date &   Debugging   Decompilers   Deep Links   Dependency Injections   Design   Design Patterns   Dex   Dialogs   Distributed Computing   Distribution Platforms   Download Managers   Drawables   Emoji   Emulators   EPUB   Equalizers &   Event Buses   Exception Handling   Face Recognition   Feedback &   File System   File/Directory   Fingerprint   Floating Action   Fonts   Forms   Fragments   FRP   FSM   Functional Programming   Gamepads   Games   Geocaching   Gestures   GIF   Glow Pad   Gradle Plugins   Graphics   Grid Views   Highlighting   HTML   HTTP Mocking   Icons   IDE   IDE Plugins   Image Croppers   Image Loaders   Image Pickers   Image Processing   Image Views   Instrumentation   Intents   Job Schedulers   JSON   Keyboard   Kotlin   Layouts   Library Demos   List View   List Views   Localization   Location   Lock Patterns   Logcat   Logging   Mails   Maps   Markdown   Mathematics   Maven Plugins   MBaaS   Media   Menus   Messaging   MIME   Mobile Web   Native Image   Navigation   NDK   Networking   NFC   NoSQL   Number Pickers   OAuth   Object Mocking   OCR Engines   OpenGL   ORM   Other Pickers   Parallax List   Parcelables   Particle Systems   Password Inputs   PDF   Permissions   Physics Engines   Platforms   Plugin Frameworks   Preferences   Progress Indicators   ProGuard   Properties   Protocol Buffer   Pull To   Purchases   Push/Pull   QR Codes   Quick Return   Radio Buttons   Range Bars   Ratings   Recycler Views   Resources   REST   Ripple Effects   RSS   Screenshots   Scripting   Scroll Views   SDK   Search Inputs   Security   Sensors   Services   Showcase Views   Signatures   Sliding Panels   Snackbars   SOAP   Social Networks   Spannable   Spinners   Splash Screens   SSH   Static Analysis   Status Bars   Styling   SVG   System   Tags   Task Managers   TDD &   Template Engines   Testing   Testing Tools   Text Formatting   Text Views   Text Watchers   Text-to   Toasts   Toolkits For   Tools   Tooltips   Trainings   TV   Twitter   Updaters   USB   User Stories   Utils   Validation   Video   View Adapters   View Pagers   Views   Watch Face   Wearable Data   Wearables   Weather   Web Tools   Web Views   WebRTC   WebSockets   Wheel Widgets   Wi-Fi   Widgets   Windows   Wizards   XML   XMPP   YAML   ZIP Codes