Giter Site home page Giter Site logo

ahmedeltaher / mvvm-kotlin-android-architecture Goto Github PK

View Code? Open in Web Editor NEW
2.3K 58.0 597.0 4.32 MB

MVVM + Kotlin + Retrofit2 + Hilt + Coroutines + Kotlin Flow + mockK + Espresso + Junit5

License: Apache License 2.0

Kotlin 87.40% HTML 0.05% Java 12.55%
mvvm mvp android-architecture android mockito espresso coroutines retrofit2 junit mockk

mvvm-kotlin-android-architecture's Introduction

Android Arsenal kotlin coroutines Mockk Junit5 Espresso Dagger 2 Kotlin-Android-Extensions MVVM MVP Build StatusMVVM3

Model-View-ViewModel (ie MVVM) is a template of a client application architecture, proposed by John Gossman as an alternative to MVC and MVP patterns when using Data Binding technology. Its concept is to separate data presentation logic from business logic by moving it into particular class for a clear distinction. You can also check MVP

Why Promoting MVVM VS MVP:

  • ViewModel has Built in LifeCycleOwerness, on the other hand Presenter not, and you have to take this responsiblty in your side.
  • ViewModel doesn't have a reference for View, on the other hand Presenter still hold a reference for view, even if you made it as weakreference.
  • ViewModel survive configuration changes, while it is your own responsiblities to survive the configuration changes in case of Presenter. (Saving and restoring the UI state)

MVVM Best Pratice:

  • Avoid references to Views in ViewModels.
  • Instead of pushing data to the UI, let the UI observe changes to it.
  • Distribute responsibilities, add a domain layer if needed.
  • Add a data repository as the single-point entry to your data.
  • Expose information about the state of your data using a wrapper or another LiveData.
  • Consider edge cases, leaks and how long-running operations can affect the instances in your architecture.
  • Don’t put logic in the ViewModel that is critical to saving clean state or related to data. Any call you make from a ViewModel can be the last one.

What is Coroutines ?

Coroutines : Is light wight threads for asynchronous programming, Coroutines not only open the doors to asynchronous programming, but also provide a wealth of other possibilities such as concurrency, actors, etc.


Coroutines VS RXJava

They're different tools with different strengths. Like a tank and a cannon, they have a lot of overlap but are more or less desirable under different circumstances. - Coroutines Is light wight threads for asynchronous programming. - RX-Kotlin/RX-Java is functional reactive programming, its core pattern relay on observer design pattern, so you can use it to handle user interaction with UI while you still using coroutines as main core for background work.

How does Coroutines concept work ?

  • Kotlin coroutine is a way of doing things asynchronously in a sequential manner. Creating a coroutine is a lot cheaper vs creating a thread.

When I can choose Coroutines or RX-Kotlin to do some behaviour ?

  • Coroutines : When we have concurrent tasks , like you would fetch data from Remote connections , database , any background processes , sure you can use RX in such cases too, but it looks like you use a tank to kill ant.
  • RX-Kotlin : When you would to handle stream of UI actions like : user scrolling , clicks , update UI upon some events .....ect .

What is the Coroutines benefits?

  • Writing an asynchronous code is sequential manner.
  • Costing of create coroutines are much cheaper to crate threads.
  • Don't be over engineered to use observable pattern, when no need to use it.
  • parent coroutine can automatically manage the life cycle of its child coroutines for you.

Handle Retrofit with Coroutines

8399

  • Add Coroutines to your gradle file
// Add Coroutines
implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.3.2'
implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-core:1.3.2'
implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-core-common:1.3.2'
// Add Retrofit2
implementation 'com.squareup.retrofit2:retrofit:2.6.2'
implementation 'com.squareup.retrofit2:converter-gson:2.6.2'
implementation 'com.squareup.okhttp3:okhttp:4.2.2'
  • Make Retrofit Calls.
    @GET("topstories/v2/home.json")
    suspend fun fetchNews(): Response<NewsModel>
  • With async we create new coroutine and returns its future result as an implementation of [Deferred].
  • The coroutine builder called launch allow us to start a coroutine in background and keep working in the meantime.
  • so async will run in background then return its promised result to parent coroutine which created by launch.
  • when we get a result, it is up to us to do handle the result.
    newsMutableLiveData.postValue(Resource.Loading())
        launch {
            try {
                serviceResponse = dataRepository.requestNews()
                newsMutableLiveData.postValue(serviceResponse)
            } catch (e: Exception) {
                newsMutableLiveData.postValue(Resource.DataError(NETWORK_ERROR))
            }
        }

Keep your code clean according to MVVM

  • Yes , liveData is easy , powerful , but you should know how to use.
  • For livedate which will emit data stream , it has to be in your data layer , and don't inform those observables any thing else like in which thread those will consume , cause it is another
  • For livedata which will emit UI binding events, it has to be in your ViewModel Layer.
  • Observers in UI Consume and react to live data values and bind it. responsibility , and according to Single responsibility principle in SOLID (object-oriented design) , so don't break this concept by mixing the responsibilities .

mvvm2

LICENSE

Copyright [2016] [Ahmed Eltaher] 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.

mvvm-kotlin-android-architecture's People

Contributors

agnamc9 avatar ahmedeltaher 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  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  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

mvvm-kotlin-android-architecture's Issues

I need help with Espresso, no place founded solution

Hi! I'm a spanish developer working in a project and I want to make first Espresso UI tests.

This is my code:

`@RunWith(AndroidJUnit4::class)
class FiltersFragmentTest {

private lateinit var sc: FragmentScenario<FiltersFragment>

@Before
fun setup() {
    sc = FragmentScenario.Companion.launchInContainer(FiltersFragment::class.java)
}

}`

Compiler errors due to FiltersFragment not inherits directly from Fragment of AndroidX, but indirectly.
The inheritance chain is
FiltersFragment is RPBaseFragment
RPBaseFragment is BaseFragment
Fragment is androidx.app.Fragment

Any clue how can i avoid this errors or is a bug from the library?
Thanks a lot!!

Refactor: separate repo for each model

Usually, we have multiple repos in the app, each responsible for a model. So for example:

  • AuthRepo
  • UserRepo
  • RecipeRepo

Same can be done to the local/remote DS, or as well as the DAOs.

The main reason for this is simply better SRP.

Currently in the app, we have only one repo, I think this can refactored.

Use of suspend function

Great job with the template
I wanted to request a modification in the current template.
Retrofit's latest version supports suspend function. Can you use the suspend function when making API calls

Thank you

refreshing on change rotation

why you dont manage refreshing data on rotation device? each change rotation device, application trying to get data from net ???

Hi ahmed ! Greetings , thanks for this wonderful project ,i just wanted to ask what if we want to use bg thread in viewModel for presentation logic , what will be the approach please suggest thanks , any way this is the first time i am asking on github if anythings is wrong please forgive thanks.

Is your feature request related to a problem? Please describe.
A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]

Describe the solution you'd like
A clear and concise description of what you want to happen.

Describe alternatives you've considered
A clear and concise description of any alternative solutions or features you've considered.

Additional context
Add any other context or screenshots about the feature request here.

Recommended multi module

Good Job, I have a note , instead struct the project based on layers, we can use multi modules instead

Hi how to used paging 3 with pagination in this project

Is your feature request related to a problem? Please describe.
A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]

Describe the solution you'd like
A clear and concise description of what you want to happen.

Describe alternatives you've considered
A clear and concise description of any alternative solutions or features you've considered.

Additional context
Add any other context or screenshots about the feature request here.

How to Use this?

A simple but powerful question, so where did you define the usage for dummies

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.