Code Monkey home page Code Monkey logo

posts's Introduction

Posts

A sample app to demonstrate the building of a good, modular and scalable Android app using Kotlin, Android Architecture Components (LiveData, ViewModel & Room), Dagger, RxJava and RxAndroid among others.

Features

Some of the features of the app include

  • Effective Networking - Using a combination of Retrofit, Rx, Room and LiveData, we are able to handle networking in the most effective way.

  • Modular - The app is broken into modules of features and libraries which can be combined to build instant-apps, complete apps or lite version of apps.

  • MVVM architecture - Using the lifecycle aware viewmodels, the view observes changes in the model / repository.

  • Kotlin - This app is completely written in Kotlin.

  • Android Architecture Components - Lifecycle awareness has been achieved using a combination of LiveData, ViewModels and Room.

  • Offline first architecture - All the data is first tried to be loaded from the db and then updated from the server. This ensures that the app is usable even in an offline mode.

  • Dependency Injection - Common elements like context, networking interface are injected using Dagger 2.

  • Feature based packaging - This screen-wise / feature-wise packaging makes code really easy to read and debug.

Working

Working

Networking

Data flow Diagram

viewModel.getPosts()
fun getPosts() {
    if (postsOutcome.value == null)
        repo.fetchPosts(compositeDisposable)
}
val postFetchOutcome: PublishSubject<Outcome<List<PostWithUser>>> = PublishSubject.create<Outcome<List<PostWithUser>>>()

private val TAG = "ListRepository"

fun fetchPosts(compositeDisposable: CompositeDisposable) {
    postFetchOutcome.loading(true)
    //Observe changes to the db
    postDb.postDao().getAll()
            .performOnBackOutOnMain()
            .subscribe({ retailers ->
                postFetchOutcome.success(retailers)
                if (remoteFetch)
                    refreshPosts(compositeDisposable)
                remoteFetch = false
            }, { error -> handleError(error) }
            .addTo(compositeDisposable)
    )
}

fun refreshPosts(compositeDisposable: CompositeDisposable) {
    postFetchOutcome.loading(true)
        Flowable.zip(
                postService.getUsers(),
                postService.getPosts(),
                BiFunction<List<User>, List<Post>, Unit> { t1, t2 -> saveUsersAndPosts(t1, t2) }
        )
                .performOnBackOutOnMain()
                .subscribe({}, { error -> handleError(error) })
                .addTo(compositeDisposable)
}

private fun saveUsersAndPosts(users: List<User>, posts: List<Post>) {
    Completable.fromAction {
        postDb.userDao().insertAll(users)
        postDb.postDao().insertAll(posts)
    }
            .performOnBackOutOnMain()
            .subscribe()
}

private fun handleError(error: Throwable) {
    postFetchOutcome.failed(error)
}
val postsOutcome: LiveData<Outcome<List<Post>>> by lazy {
    //Convert publish subject to livedata
    repo.postFetchOutcome.toLiveData(compositeDisposable)
}
viewModel.postsOutcome.observe(this, Observer<Outcome<List<Post>>> { outcome ->
        when (outcome) {

            is Outcome.Progress -> srlPosts.isRefreshing = outcome.loading

            is Outcome.Success -> {
                Log.d(TAG, "initiateDataListener: Successfully loaded data")
                adapter.setData(outcome.data)
            }

            is Outcome.Failure -> {
                if (outcome.e is IOException)
                    Toast.makeText(context, R.string.need_internet_posts, Toast.LENGTH_LONG).show()
                else
                    Toast.makeText(context, R.string.failed_post_try_again, Toast.LENGTH_LONG).show()
            }

        }
    })

Testing:

TODO

Build info:

  • Android Studio - 3.1 Canary 8
  • Compile SDK - 27
  • MinSDK - 16, Target - 27

Libraries used

License

Copyright 2018 Karan Trehan

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.

posts's People

Contributors

karntrehan avatar dellisd avatar

Watchers

James Cloos avatar

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.