Usecases


Source link: https://github.com/Zeyad-37/UseCases

UseCases

Is a library that is a generic implementation of the Domain and Data layers in a clean architecture.

Motivation

As developers, we always need to deliver high quality software on time, which is not an easy task. In most tasks, we need to make either a IO operation, whether from the server, db or file, which is a lot of boiler plate. And getting it functioning and effiecient every time is a bit challenging due to the many things that you need to take care of. Like separation of concerns, error handling and writing robust code that would not crash on you. I have noticed that this code repeats almost with every user story, and i was basically re-writing the same code, but for different models. So i thought what if i could pass the class with the request and not repeat this code over and over. Hence, please welcome the UseCases lib.

Requirements

UseCases Library can be included in any Android application that supports Android 2.3 (Gingerbread) and later.

Installation

Easiest way to start

// Create Class LibraryModule to expose your realm models to the lib configuration  @RealmModule(library = true, allClasses = true) class LibraryModule {
 
}
 
// This should be in the application class  Realm.init(this);
 // First initialize realm Realm.setDefaultConfiguration(new RealmConfiguration.Builder()

 .name("app.realm")

 .modules(Realm.getDefaultModule(), new LibraryModule())

 .rxFactory(new RealmObservableFactory())

 .deleteRealmIfMigrationNeeded()

 .build());
  // Fastest start DataServiceFactory.init(new DataUseCaseConfig.Builder(applicationContext).build());
 // all extra features are disabled

// Advanced init DataServiceFactory.init(new DataServiceConfig.Builder(applicationContext)

  .baseUrl(API_BASE_URL)

.withRealm() // if you want a DB

  .withCache(3, TimeUnit.MINUTES) // adds a cache layer above the server & DB if exists

  .cacheSize(8192)  // maximum size to allocate in bytes

  .okHttpBuilder(provideOkHttpClientBuilder())

.okhttpCache(provideCache()) // you can also provide a cache for okHttp

  .postExecutionThread(AndroidScheduler.mainThread()) // your implementation of the post execution thread

  .build());
 DataServiceFactory.getInstance();
 

Code Example

Get Object From Server:

mDataService.<Order>getObject(new GetRequest

.GetRequestBuilder(Order.class, true) // true to save result to db, false otherwise.

.url(URL) // if you provided a base url in the DataServiceConfig.Builder

.idColumnName(Order.ID)

.id(orderId)

.build())

.subscribe(new Subscriber<Order>() {

 @Override

 public void onCompleted() {

 
}

  @Override

 public void onError(Throwable e) {

  e.printStackTrace();

 
}

  @Override

 public void onNext(Order order) {

 
}

}
);
 

Get Object From DB:

mDataService.<Order>getObject(new GetRequest

.GetRequestBuilder(Order.class, true)

.idColumnName(Order.ID)

.id(mItemId)

.build());
 

Get List From Server:

mDataService.<Order>getList(new GetRequest

.GetRequestBuilder(Order.class, false)

.fullUrl(FULL_URL) // for server access

.build())

.subscribe(new Subscriber<List<Order>>() {

 @Override

 public void onCompleted() {

 
}

  @Override

 public void onError(Throwable e) {

  e.printStackTrace();

 
}

  @Override

 public void onNext(List<Order> order){

 
}

}
);
 

Get List From DB:

mDataService.<Order>getList(new GetRequest

.GetRequestBuilder(Order.class, false)

.build());
 

Post/Put Object:

mDataService.<MyResponse>postObject(new PostRequest // putObject

.PostRequestBuilder(Payload.class, true) // Type of expected server response

.idColumnName(Order.ID) // for persistance

.url(URL) // remove for DB access

.payLoad(order) // or HashMap / JSONObject

.responseType(MyResponse.class)

.build());
 

Post/Put List:

mDataService.<MyResponse>postList(new PostRequest // putList

.PostRequestBuilder(Payload.class, true) // Type of expected server response

.payLoad(orders)

.idColumnName(Order.ID) // for persistance

.url(URL) // remove for DB access

.responseType(MyResponse.class)

.build()) 

Delete Collection

mDataService().<MyResponse>deleteCollectionByIds(new PostRequest // putList

.PostRequestBuilder(Payload.class, true)

.payLoad(ids)

.idColumnName(Order.ID) // for persistance

.url(URL) // remove for DB access

.responseType(MyResponse.class)

.build()) 

Delete Item:

mDataService().<MyResponse>deleteCollectionByIds(new PostRequest // putList

.PostRequestBuilder(Payload.class, true)

.payLoad(id)

.idColumnName(Order.ID) // for persistance

.url(URL) // remove for DB access

.responseType(MyResponse.class)

.build()) 

Delete All from DB:

mDataService.deleteAll(new PostRequest

.PostRequestBuilder(Order.class, true)

.idColumnName(Order.ID)

.build()) 

Upload File

mDataService.<MyResponse>uploadFile(new FileIORequest

.FileIORequestBuilder(FULL_URL, new File()) // always full url

.onWifi(true)

.whileCharging(false)

.responseType(MyResponse.class)

.build()) 

Download File

mDataService.downloadFile(new FileIORequest

.FileIORequestBuilder(FULL_URL, new File())

.onWifi(true)

.whileCharging(false)

.requestType(Order.class)

.build()) 

Contributors

Just make pull request. You are in!

License

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

Resources

A RecyclerView with support of addHeaderView and addFooterView features.

Demo app for Deep dive into Android Data Binding talk.

Don't write a RecyclerView adapter again. Not even a ViewHolder!

  • Based on Android Data Binding
  • Written in Kotlin
  • No need to write the adapter
  • No need to write the viewholders
  • No need to modify your model classes
  • No need to notify the adapter when data set changed
  • Supports multiple view types
  • Manage item click/long-click in layout or builder
  • Optional OnBindListener's
  • Very fast -- no reflection
  • Super easy API
  • Tiny size: 31 KB
  • Minimum Android SDK: 9

Helper class to configure cache behaviour of OkHttp client, also works with Retrofit for Android.

A simple Firebase chat application for Android.

Pop animation with circular dust effect for any view update.

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