├── app
├── .gitignore
├── src
│ ├── main
│ │ ├── res
│ │ │ ├── values
│ │ │ │ ├── strings.xml
│ │ │ │ ├── colors.xml
│ │ │ │ └── styles.xml
│ │ │ ├── mipmap-hdpi
│ │ │ │ ├── ic_launcher.png
│ │ │ │ └── ic_launcher_round.png
│ │ │ ├── mipmap-mdpi
│ │ │ │ ├── ic_launcher.png
│ │ │ │ └── ic_launcher_round.png
│ │ │ ├── mipmap-xhdpi
│ │ │ │ ├── ic_launcher.png
│ │ │ │ └── ic_launcher_round.png
│ │ │ ├── mipmap-xxhdpi
│ │ │ │ ├── ic_launcher.png
│ │ │ │ └── ic_launcher_round.png
│ │ │ ├── mipmap-xxxhdpi
│ │ │ │ ├── ic_launcher.png
│ │ │ │ └── ic_launcher_round.png
│ │ │ └── layout
│ │ │ │ ├── activity_post_list.xml
│ │ │ │ ├── item_post.xml
│ │ │ │ └── activity_post_detail.xml
│ │ ├── kotlin
│ │ │ └── com
│ │ │ │ └── blacklenspub
│ │ │ │ └── postsreader
│ │ │ │ ├── util
│ │ │ │ ├── Logger.kt
│ │ │ │ ├── LoggerImpl.kt
│ │ │ │ └── UtilModule.kt
│ │ │ │ ├── data
│ │ │ │ ├── PostRepository.kt
│ │ │ │ ├── local
│ │ │ │ │ ├── AppDatabase.kt
│ │ │ │ │ └── PostDao.kt
│ │ │ │ ├── remote
│ │ │ │ │ └── PostsReaderApi.kt
│ │ │ │ ├── entity
│ │ │ │ │ └── Post.kt
│ │ │ │ ├── di
│ │ │ │ │ ├── PostRepositoryModule.kt
│ │ │ │ │ ├── LocalDataModule.kt
│ │ │ │ │ └── RemoteDataModule.kt
│ │ │ │ └── PostRepositoryImpl.kt
│ │ │ │ ├── presentation
│ │ │ │ ├── PageNavigator.kt
│ │ │ │ ├── postdetail
│ │ │ │ │ ├── PostDetailViewModel.kt
│ │ │ │ │ └── PostDetailActivity.kt
│ │ │ │ ├── postlist
│ │ │ │ │ ├── PostListViewModel.kt
│ │ │ │ │ ├── PostAdapter.kt
│ │ │ │ │ └── PostListActivity.kt
│ │ │ │ └── di
│ │ │ │ │ └── AppComponent.kt
│ │ │ │ └── PostsReaderApplication.kt
│ │ └── AndroidManifest.xml
│ ├── androidTest
│ │ └── java
│ │ │ └── com
│ │ │ └── blacklenspub
│ │ │ └── postsreader
│ │ │ └── ExampleInstrumentedTest.java
│ └── test
│ │ └── kotlin
│ │ └── com
│ │ └── blacklenspub
│ │ └── postsreader
│ │ ├── presentation
│ │ ├── postdetail
│ │ │ └── PostDetailViewModelTest.kt
│ │ └── postlist
│ │ │ └── PostListViewModelTest.kt
│ │ └── data
│ │ └── PostRepositoryImplTest.kt
├── proguard-rules.pro
└── build.gradle
├── settings.gradle
├── gradle
└── wrapper
│ ├── gradle-wrapper.jar
│ └── gradle-wrapper.properties
├── .gitignore
├── dependencies.gradle
├── gradle.properties
├── README.md
├── gradlew.bat
└── gradlew
/app/.gitignore:
--------------------------------------------------------------------------------
1 | /build
2 |
--------------------------------------------------------------------------------
/settings.gradle:
--------------------------------------------------------------------------------
1 | include ':app'
2 |
--------------------------------------------------------------------------------
/app/src/main/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
2 | PostsReader
3 |
4 |
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/dewparin/posts-reader/HEAD/gradle/wrapper/gradle-wrapper.jar
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | *.iml
2 | .gradle
3 | /local.properties
4 | /.idea
5 | .DS_Store
6 | /build
7 | /captures
8 | .externalNativeBuild
9 |
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-hdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/dewparin/posts-reader/HEAD/app/src/main/res/mipmap-hdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-mdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/dewparin/posts-reader/HEAD/app/src/main/res/mipmap-mdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/dewparin/posts-reader/HEAD/app/src/main/res/mipmap-xhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/dewparin/posts-reader/HEAD/app/src/main/res/mipmap-xxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/dewparin/posts-reader/HEAD/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-hdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/dewparin/posts-reader/HEAD/app/src/main/res/mipmap-hdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-mdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/dewparin/posts-reader/HEAD/app/src/main/res/mipmap-mdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xhdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/dewparin/posts-reader/HEAD/app/src/main/res/mipmap-xhdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/dewparin/posts-reader/HEAD/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/dewparin/posts-reader/HEAD/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/app/src/main/kotlin/com/blacklenspub/postsreader/util/Logger.kt:
--------------------------------------------------------------------------------
1 | package com.blacklenspub.postsreader.util
2 |
3 | interface Logger {
4 |
5 | fun logDebug(tag: String, message: String)
6 | }
7 |
8 |
--------------------------------------------------------------------------------
/app/src/main/res/values/colors.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | #3F51B5
4 | #303F9F
5 | #FF4081
6 |
7 |
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.properties:
--------------------------------------------------------------------------------
1 | #Mon Jun 05 11:30:15 ICT 2017
2 | distributionBase=GRADLE_USER_HOME
3 | distributionPath=wrapper/dists
4 | zipStoreBase=GRADLE_USER_HOME
5 | zipStorePath=wrapper/dists
6 | distributionUrl=https\://services.gradle.org/distributions/gradle-3.3-all.zip
7 |
--------------------------------------------------------------------------------
/app/src/main/kotlin/com/blacklenspub/postsreader/util/LoggerImpl.kt:
--------------------------------------------------------------------------------
1 | package com.blacklenspub.postsreader.util
2 |
3 | import android.util.Log
4 |
5 | class LoggerImpl : Logger {
6 |
7 | override fun logDebug(tag: String, message: String) {
8 | Log.d(tag, message)
9 | }
10 | }
11 |
12 |
--------------------------------------------------------------------------------
/app/src/main/kotlin/com/blacklenspub/postsreader/util/UtilModule.kt:
--------------------------------------------------------------------------------
1 | package com.blacklenspub.postsreader.util
2 |
3 | import dagger.Module
4 | import dagger.Provides
5 | import javax.inject.Singleton
6 |
7 | @Module
8 | class UtilModule {
9 |
10 | @Provides @Singleton
11 | fun provideLogger(): Logger = LoggerImpl()
12 | }
13 |
14 |
--------------------------------------------------------------------------------
/app/src/main/kotlin/com/blacklenspub/postsreader/data/PostRepository.kt:
--------------------------------------------------------------------------------
1 | package com.blacklenspub.postsreader.data
2 |
3 | import android.arch.lifecycle.LiveData
4 | import com.blacklenspub.postsreader.data.entity.Post
5 |
6 | interface PostRepository {
7 |
8 | fun insertOrUpdate(post: Post)
9 |
10 | fun getAllPosts(): LiveData>
11 |
12 | fun getPostById(id: String): LiveData
13 | }
14 |
--------------------------------------------------------------------------------
/app/src/main/res/values/styles.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
10 |
11 |
12 |
--------------------------------------------------------------------------------
/app/src/main/kotlin/com/blacklenspub/postsreader/data/local/AppDatabase.kt:
--------------------------------------------------------------------------------
1 | package com.blacklenspub.postsreader.data.local
2 |
3 | import android.arch.persistence.room.Database
4 | import android.arch.persistence.room.RoomDatabase
5 | import com.blacklenspub.postsreader.data.entity.Post
6 |
7 | @Database(entities = arrayOf(Post::class), version = 1)
8 | abstract class AppDatabase : RoomDatabase() {
9 |
10 | abstract fun postDao(): PostDao
11 | }
12 |
13 |
--------------------------------------------------------------------------------
/dependencies.gradle:
--------------------------------------------------------------------------------
1 | ext {
2 |
3 | buildToolsVersion = '25.0.3'
4 | minSdkVersion = 19
5 | targetSdkVersion = 25
6 | compileSdkVersion = 25
7 |
8 | junitVersion = '4.12'
9 | mockitoVersion = '2.8.9'
10 | espressoVersion = '2.2.2'
11 |
12 | supportLibVersion = '25.3.1'
13 | constraintLayoutVersion = '1.0.2'
14 | architectureComponentsVersion = '1.0.0-alpha2'
15 |
16 | retrofitVersion = '2.3.0'
17 |
18 | daggerVersion = '2.11'
19 | }
--------------------------------------------------------------------------------
/app/src/main/kotlin/com/blacklenspub/postsreader/data/remote/PostsReaderApi.kt:
--------------------------------------------------------------------------------
1 | package com.blacklenspub.postsreader.data.remote
2 |
3 | import com.blacklenspub.postsreader.data.entity.Post
4 | import io.reactivex.Single
5 | import retrofit2.http.GET
6 | import retrofit2.http.Path
7 |
8 | interface PostsReaderApi {
9 |
10 | @GET("posts")
11 | fun getAllPosts(): Single>
12 |
13 | @GET("posts/{id}")
14 | fun getPostById(@Path("id") id: String): Single
15 | }
16 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/activity_post_list.xml:
--------------------------------------------------------------------------------
1 |
2 |
6 |
7 |
11 |
12 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/item_post.xml:
--------------------------------------------------------------------------------
1 |
2 |
7 |
8 |
12 |
13 |
--------------------------------------------------------------------------------
/app/src/main/kotlin/com/blacklenspub/postsreader/presentation/PageNavigator.kt:
--------------------------------------------------------------------------------
1 | package com.blacklenspub.postsreader.presentation
2 |
3 | import android.content.Context
4 | import android.content.Intent
5 | import com.blacklenspub.postsreader.presentation.postdetail.PostDetailActivity
6 |
7 | object PageNavigator {
8 |
9 | fun gotoPostDetailActivity(context: Context, postId: String) {
10 | val intent = Intent(context, PostDetailActivity::class.java).apply {
11 | putExtra(PostDetailActivity.KEY_POST_ID, postId)
12 | }
13 | context.startActivity(intent)
14 | }
15 | }
16 |
17 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/activity_post_detail.xml:
--------------------------------------------------------------------------------
1 |
2 |
6 |
7 |
12 |
13 |
18 |
19 |
--------------------------------------------------------------------------------
/app/src/main/kotlin/com/blacklenspub/postsreader/data/entity/Post.kt:
--------------------------------------------------------------------------------
1 | package com.blacklenspub.postsreader.data.entity
2 |
3 | import android.arch.persistence.room.ColumnInfo
4 | import android.arch.persistence.room.Entity
5 | import android.arch.persistence.room.PrimaryKey
6 | import com.google.gson.annotations.SerializedName
7 |
8 | @Entity(tableName = "post")
9 | class Post {
10 |
11 | @PrimaryKey
12 | @ColumnInfo(name = "id")
13 | @SerializedName("id")
14 | lateinit var id: String
15 |
16 | @ColumnInfo(name = "title")
17 | @SerializedName("title")
18 | lateinit var title: String
19 |
20 | @ColumnInfo(name = "body")
21 | @SerializedName("body")
22 | lateinit var body: String
23 | }
24 |
--------------------------------------------------------------------------------
/app/src/main/kotlin/com/blacklenspub/postsreader/data/di/PostRepositoryModule.kt:
--------------------------------------------------------------------------------
1 | package com.blacklenspub.postsreader.data.di
2 |
3 | import com.blacklenspub.postsreader.data.PostRepository
4 | import com.blacklenspub.postsreader.data.PostRepositoryImpl
5 | import com.blacklenspub.postsreader.data.local.PostDao
6 | import com.blacklenspub.postsreader.data.remote.PostsReaderApi
7 | import dagger.Module
8 | import dagger.Provides
9 | import io.reactivex.schedulers.Schedulers
10 | import javax.inject.Singleton
11 |
12 | @Module
13 | class PostRepositoryModule {
14 |
15 | @Provides @Singleton
16 | fun providePostRepository(localSource: PostDao, remoteSource: PostsReaderApi): PostRepository
17 | = PostRepositoryImpl(localSource, remoteSource, Schedulers.io())
18 | }
19 |
20 |
--------------------------------------------------------------------------------
/gradle.properties:
--------------------------------------------------------------------------------
1 | # Project-wide Gradle settings.
2 |
3 | # IDE (e.g. Android Studio) users:
4 | # Gradle settings configured through the IDE *will override*
5 | # any settings specified in this file.
6 |
7 | # For more details on how to configure your build environment visit
8 | # http://www.gradle.org/docs/current/userguide/build_environment.html
9 |
10 | # Specifies the JVM arguments used for the daemon process.
11 | # The setting is particularly useful for tweaking memory settings.
12 | org.gradle.jvmargs=-Xmx1536m
13 |
14 | # When configured, Gradle will run in incubating parallel mode.
15 | # This option should only be used with decoupled projects. More details, visit
16 | # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
17 | # org.gradle.parallel=true
18 |
--------------------------------------------------------------------------------
/app/src/main/kotlin/com/blacklenspub/postsreader/data/local/PostDao.kt:
--------------------------------------------------------------------------------
1 | package com.blacklenspub.postsreader.data.local
2 |
3 | import android.arch.lifecycle.LiveData
4 | import android.arch.persistence.room.Dao
5 | import android.arch.persistence.room.Insert
6 | import android.arch.persistence.room.OnConflictStrategy
7 | import android.arch.persistence.room.Query
8 | import com.blacklenspub.postsreader.data.entity.Post
9 |
10 | @Dao
11 | interface PostDao {
12 |
13 | @Insert(onConflict = OnConflictStrategy.REPLACE)
14 | fun insertOrUpdatePosts(vararg posts: Post)
15 |
16 | @Query("SELECT * FROM post")
17 | fun getAllPosts(): LiveData>
18 |
19 | // id is changed to arg0 in generated code
20 | @Query("SELECT * FROM post WHERE id = :arg0")
21 | fun getPostById(id: String): LiveData
22 | }
23 |
24 |
--------------------------------------------------------------------------------
/app/src/main/kotlin/com/blacklenspub/postsreader/data/di/LocalDataModule.kt:
--------------------------------------------------------------------------------
1 | package com.blacklenspub.postsreader.data.di
2 |
3 | import android.arch.persistence.room.Room
4 | import android.content.Context
5 | import com.blacklenspub.postsreader.data.local.AppDatabase
6 | import com.blacklenspub.postsreader.data.local.PostDao
7 | import dagger.Module
8 | import dagger.Provides
9 | import javax.inject.Singleton
10 |
11 | @Module
12 | class LocalDataModule(val context: Context) {
13 |
14 | private val DB_FILE_NAME = "posts-reader-db"
15 |
16 | @Provides @Singleton
17 | fun providePostDao(db: AppDatabase): PostDao = db.postDao()
18 |
19 | @Provides @Singleton
20 | fun provideAppDatabase(): AppDatabase =
21 | Room.databaseBuilder(context.applicationContext, AppDatabase::class.java, DB_FILE_NAME)
22 | .build()
23 | }
24 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # posts-reader
2 | Written in [Kotlin](https://kotlinlang.org/), Android architecture sample app using [Android Architecture Components](https://developer.android.com/topic/libraries/architecture/index.html), [RxJava2](https://github.com/ReactiveX/RxJava) and [Dagger2](https://google.github.io/dagger/) plus sample unit tests using JUnit and [Mockito](http://site.mockito.org/).
3 |
4 | This app consumes data from [JSONPlaceholder](http://jsonplaceholder.typicode.com/).
5 |
6 | [Related blog post (Thai language)](https://medium.com/p/d89302734ab8/).
7 |
8 | ## Screenshot
9 |
10 | 
11 |
12 | ## Final Architecture
13 |
14 | 
15 |
--------------------------------------------------------------------------------
/app/src/androidTest/java/com/blacklenspub/postsreader/ExampleInstrumentedTest.java:
--------------------------------------------------------------------------------
1 | package com.blacklenspub.postsreader;
2 |
3 | import android.content.Context;
4 | import android.support.test.InstrumentationRegistry;
5 | import android.support.test.runner.AndroidJUnit4;
6 |
7 | import org.junit.Test;
8 | import org.junit.runner.RunWith;
9 |
10 | import static org.junit.Assert.*;
11 |
12 | /**
13 | * Instrumentation test, which will execute on an Android device.
14 | *
15 | * @see Testing documentation
16 | */
17 | @RunWith(AndroidJUnit4.class)
18 | public class ExampleInstrumentedTest {
19 | @Test
20 | public void useAppContext() throws Exception {
21 | // Context of the app under test.
22 | Context appContext = InstrumentationRegistry.getTargetContext();
23 |
24 | assertEquals("com.blacklenspub.postsreader", appContext.getPackageName());
25 | }
26 | }
27 |
--------------------------------------------------------------------------------
/app/src/main/kotlin/com/blacklenspub/postsreader/data/di/RemoteDataModule.kt:
--------------------------------------------------------------------------------
1 | package com.blacklenspub.postsreader.data.di
2 |
3 | import com.blacklenspub.postsreader.data.remote.PostsReaderApi
4 | import dagger.Module
5 | import dagger.Provides
6 | import retrofit2.Retrofit
7 | import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory
8 | import retrofit2.converter.gson.GsonConverterFactory
9 | import javax.inject.Singleton
10 |
11 | @Module
12 | class RemoteDataModule(val baseUrl: String) {
13 |
14 | @Provides @Singleton
15 | fun providePostsReaderApi(retrofit: Retrofit): PostsReaderApi
16 | = retrofit.create(PostsReaderApi::class.java)
17 |
18 | @Provides @Singleton
19 | fun provideRetrofit(): Retrofit
20 | = Retrofit.Builder()
21 | .baseUrl(baseUrl)
22 | .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
23 | .addConverterFactory(GsonConverterFactory.create())
24 | .build()
25 | }
26 |
27 |
--------------------------------------------------------------------------------
/app/src/main/kotlin/com/blacklenspub/postsreader/presentation/postdetail/PostDetailViewModel.kt:
--------------------------------------------------------------------------------
1 | package com.blacklenspub.postsreader.presentation.postdetail
2 |
3 | import android.arch.lifecycle.LiveData
4 | import android.arch.lifecycle.ViewModel
5 | import com.blacklenspub.postsreader.data.PostRepository
6 | import com.blacklenspub.postsreader.data.entity.Post
7 | import javax.inject.Inject
8 |
9 | class PostDetailViewModel : ViewModel() {
10 |
11 | @Inject
12 | lateinit var postRepo: PostRepository
13 |
14 | private var post: LiveData? = null
15 |
16 | fun getPostDetail(postId: String): LiveData {
17 | // This is a simple way to cache data. You could cache it in db instead.
18 | post = post ?: postRepo.getPostById(postId)
19 | return post!! // Don't worry I'm a good Engineer ;-)
20 | }
21 |
22 | // This function is for demonstration purpose only.
23 | fun updatePost(post: Post) {
24 | postRepo.insertOrUpdate(post)
25 | }
26 | }
27 |
28 |
--------------------------------------------------------------------------------
/app/proguard-rules.pro:
--------------------------------------------------------------------------------
1 | # Add project specific ProGuard rules here.
2 | # By default, the flags in this file are appended to flags specified
3 | # in /Users/dewparin/Library/Android/sdk/tools/proguard/proguard-android.txt
4 | # You can edit the include path and order by changing the proguardFiles
5 | # directive in build.gradle.
6 | #
7 | # For more details, see
8 | # http://developer.android.com/guide/developing/tools/proguard.html
9 |
10 | # Add any project specific keep options here:
11 |
12 | # If your project uses WebView with JS, uncomment the following
13 | # and specify the fully qualified class name to the JavaScript interface
14 | # class:
15 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview {
16 | # public *;
17 | #}
18 |
19 | # Uncomment this to preserve the line number information for
20 | # debugging stack traces.
21 | #-keepattributes SourceFile,LineNumberTable
22 |
23 | # If you keep the line number information, uncomment this to
24 | # hide the original source file name.
25 | #-renamesourcefileattribute SourceFile
26 |
--------------------------------------------------------------------------------
/app/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
4 |
5 |
6 |
7 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
--------------------------------------------------------------------------------
/app/src/main/kotlin/com/blacklenspub/postsreader/presentation/postlist/PostListViewModel.kt:
--------------------------------------------------------------------------------
1 | package com.blacklenspub.postsreader.presentation.postlist
2 |
3 | import android.arch.lifecycle.LiveData
4 | import android.arch.lifecycle.ViewModel
5 | import com.blacklenspub.postsreader.data.PostRepository
6 | import com.blacklenspub.postsreader.data.entity.Post
7 | import com.blacklenspub.postsreader.util.Logger
8 | import javax.inject.Inject
9 |
10 | class PostListViewModel : ViewModel() {
11 |
12 | private val TAG = "show_time"
13 |
14 | @Inject lateinit var logger: Logger
15 | @Inject lateinit var postRepo: PostRepository
16 |
17 | private var counter = 0
18 | private var posts: LiveData>? = null
19 |
20 | fun getAllPosts(): LiveData> {
21 | // this is for demonstration purpose only
22 | counter++
23 | logger.logDebug(TAG, "Counter: $counter")
24 |
25 | // This is a simple way to cache data. You could cache it in db instead.
26 | posts = posts ?: postRepo.getAllPosts()
27 | return posts!! // Trust me I'm an Engineer ;-)
28 | }
29 | }
30 |
--------------------------------------------------------------------------------
/app/src/main/kotlin/com/blacklenspub/postsreader/presentation/di/AppComponent.kt:
--------------------------------------------------------------------------------
1 | package com.blacklenspub.postsreader.presentation.di
2 |
3 | import com.blacklenspub.postsreader.data.di.LocalDataModule
4 | import com.blacklenspub.postsreader.data.di.PostRepositoryModule
5 | import com.blacklenspub.postsreader.data.di.RemoteDataModule
6 | import com.blacklenspub.postsreader.presentation.postdetail.PostDetailViewModel
7 | import com.blacklenspub.postsreader.presentation.postlist.PostListViewModel
8 | import com.blacklenspub.postsreader.util.Logger
9 | import com.blacklenspub.postsreader.util.UtilModule
10 | import dagger.Component
11 | import javax.inject.Singleton
12 |
13 | @Singleton
14 | @Component(
15 | modules = arrayOf(
16 | UtilModule::class,
17 |
18 | LocalDataModule::class,
19 | RemoteDataModule::class,
20 |
21 | PostRepositoryModule::class
22 | )
23 | )
24 | interface AppComponent {
25 |
26 | val logger: Logger
27 |
28 | fun inject(postListViewModel: PostListViewModel)
29 |
30 | fun inject(postDetailViewModel: PostDetailViewModel)
31 | }
32 |
33 |
--------------------------------------------------------------------------------
/app/src/main/kotlin/com/blacklenspub/postsreader/PostsReaderApplication.kt:
--------------------------------------------------------------------------------
1 | package com.blacklenspub.postsreader
2 |
3 | import android.app.Application
4 | import com.blacklenspub.postsreader.data.di.LocalDataModule
5 | import com.blacklenspub.postsreader.data.di.PostRepositoryModule
6 | import com.blacklenspub.postsreader.data.di.RemoteDataModule
7 | import com.blacklenspub.postsreader.presentation.di.AppComponent
8 | import com.blacklenspub.postsreader.presentation.di.DaggerAppComponent
9 | import com.blacklenspub.postsreader.util.UtilModule
10 |
11 | class PostsReaderApplication : Application() {
12 |
13 | companion object {
14 | lateinit var component: AppComponent
15 | }
16 |
17 | private val BASE_URL = "http://jsonplaceholder.typicode.com"
18 |
19 | override fun onCreate() {
20 | super.onCreate()
21 | buildDependencyGraph()
22 | }
23 |
24 | private fun buildDependencyGraph() {
25 | component = DaggerAppComponent.builder()
26 | .utilModule(UtilModule())
27 | .localDataModule(LocalDataModule(applicationContext))
28 | .remoteDataModule(RemoteDataModule(BASE_URL))
29 | .postRepositoryModule(PostRepositoryModule())
30 | .build()
31 | }
32 | }
33 |
34 |
--------------------------------------------------------------------------------
/app/src/main/kotlin/com/blacklenspub/postsreader/data/PostRepositoryImpl.kt:
--------------------------------------------------------------------------------
1 | package com.blacklenspub.postsreader.data
2 |
3 | import android.arch.lifecycle.LiveData
4 | import com.blacklenspub.postsreader.data.entity.Post
5 | import com.blacklenspub.postsreader.data.local.PostDao
6 | import com.blacklenspub.postsreader.data.remote.PostsReaderApi
7 | import io.reactivex.Scheduler
8 |
9 | class PostRepositoryImpl(val localSource: PostDao, val remoteSource: PostsReaderApi, val scheduler: Scheduler) : PostRepository {
10 |
11 | override fun insertOrUpdate(post: Post) {
12 | localSource.insertOrUpdatePosts(post)
13 | }
14 |
15 | override fun getAllPosts(): LiveData> {
16 | remoteSource.getAllPosts()
17 | .subscribeOn(scheduler)
18 | .subscribe { posts, _ ->
19 | posts?.let { localSource.insertOrUpdatePosts(*posts.toTypedArray()) }
20 | }
21 | return localSource.getAllPosts()
22 | }
23 |
24 | override fun getPostById(id: String): LiveData {
25 | remoteSource.getPostById(id)
26 | .subscribeOn(scheduler)
27 | .subscribe { post, _ ->
28 | post?.let { localSource.insertOrUpdatePosts(post) }
29 | }
30 | return localSource.getPostById(id)
31 | }
32 | }
33 |
34 |
--------------------------------------------------------------------------------
/app/src/main/kotlin/com/blacklenspub/postsreader/presentation/postlist/PostAdapter.kt:
--------------------------------------------------------------------------------
1 | package com.blacklenspub.postsreader.presentation.postlist
2 |
3 | import android.support.v7.widget.RecyclerView
4 | import android.view.LayoutInflater
5 | import android.view.View
6 | import android.view.ViewGroup
7 | import android.widget.TextView
8 | import com.blacklenspub.postsreader.R
9 | import com.blacklenspub.postsreader.data.entity.Post
10 | import kotlin.properties.Delegates
11 |
12 | class PostAdapter : RecyclerView.Adapter() {
13 |
14 | var posts by Delegates.observable(listOf()) { _, _, _ -> notifyDataSetChanged() }
15 | var onPostClickListener: ((id: String) -> Unit)? = null
16 |
17 | override fun getItemCount() = posts.size
18 |
19 | override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
20 | val view = LayoutInflater.from(parent.context).inflate(R.layout.item_post, parent, false)
21 | return ViewHolder(view, onPostClickListener)
22 | }
23 |
24 | override fun onBindViewHolder(holder: ViewHolder, position: Int) {
25 | holder.post = posts[position]
26 | }
27 |
28 | class ViewHolder(view: View, onPostClickListener: ((id: String) -> Unit)?) : RecyclerView.ViewHolder(view) {
29 |
30 | private val tvTitle: TextView = view.findViewById(R.id.tvPostTitle) as TextView
31 |
32 | var post: Post by Delegates.observable(Post()) { _, _, postItem ->
33 | tvTitle.text = postItem.title
34 | }
35 |
36 | init {
37 | view.setOnClickListener { onPostClickListener?.invoke(post.id) }
38 | }
39 | }
40 | }
41 |
42 |
--------------------------------------------------------------------------------
/app/build.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: 'com.android.application'
2 | apply plugin: 'kotlin-android'
3 | apply plugin: 'kotlin-android-extensions'
4 |
5 | android {
6 | compileSdkVersion rootProject.ext.compileSdkVersion
7 | buildToolsVersion rootProject.ext.buildToolsVersion
8 | defaultConfig {
9 | applicationId "com.blacklenspub.postsreader"
10 | minSdkVersion rootProject.ext.minSdkVersion
11 | targetSdkVersion rootProject.ext.targetSdkVersion
12 | versionCode 1
13 | versionName "1.0"
14 | testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
15 | }
16 | buildTypes {
17 | release {
18 | minifyEnabled false
19 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
20 | }
21 | }
22 | sourceSets {
23 | main.java.srcDirs += 'src/main/kotlin'
24 | test.java.srcDirs += 'src/test/kotlin'
25 | }
26 | }
27 | kapt {
28 | generateStubs = true
29 | }
30 | dependencies {
31 | compile fileTree(dir: 'libs', include: ['*.jar'])
32 |
33 | compile "org.jetbrains.kotlin:kotlin-stdlib-jre7:$kotlin_version"
34 |
35 | testCompile "junit:junit:$junitVersion"
36 | testCompile "org.mockito:mockito-core:$mockitoVersion"
37 | testCompile "android.arch.core:core-testing:$architectureComponentsVersion"
38 | androidTestCompile("com.android.support.test.espresso:espresso-core:$espressoVersion", {
39 | exclude group: 'com.android.support', module: 'support-annotations'
40 | })
41 |
42 | compile "com.android.support:appcompat-v7:$supportLibVersion"
43 | compile "com.android.support:recyclerview-v7:$supportLibVersion"
44 | compile "com.android.support.constraint:constraint-layout:$constraintLayoutVersion"
45 |
46 | compile "com.google.dagger:dagger:$daggerVersion"
47 | kapt "com.google.dagger:dagger-compiler:$daggerVersion"
48 |
49 | compile "android.arch.lifecycle:runtime:$architectureComponentsVersion"
50 | compile "android.arch.lifecycle:extensions:$architectureComponentsVersion"
51 | annotationProcessor "android.arch.lifecycle:compiler:$architectureComponentsVersion"
52 |
53 | compile "android.arch.persistence.room:runtime:$architectureComponentsVersion"
54 | kapt "android.arch.persistence.room:compiler:$architectureComponentsVersion"
55 |
56 | compile "com.squareup.retrofit2:retrofit:$retrofitVersion"
57 | compile "com.squareup.retrofit2:converter-gson:$retrofitVersion"
58 | compile "com.squareup.retrofit2:adapter-rxjava2:$retrofitVersion"
59 | }
60 | repositories {
61 | mavenCentral()
62 | }
63 |
--------------------------------------------------------------------------------
/app/src/main/kotlin/com/blacklenspub/postsreader/presentation/postlist/PostListActivity.kt:
--------------------------------------------------------------------------------
1 | package com.blacklenspub.postsreader.presentation.postlist
2 |
3 | import android.arch.lifecycle.LifecycleActivity
4 | import android.arch.lifecycle.Observer
5 | import android.arch.lifecycle.ViewModelProviders
6 | import android.os.Bundle
7 | import android.support.v7.widget.DividerItemDecoration
8 | import android.support.v7.widget.LinearLayoutManager
9 | import android.widget.Toast
10 | import com.blacklenspub.postsreader.PostsReaderApplication
11 | import com.blacklenspub.postsreader.R
12 | import com.blacklenspub.postsreader.data.entity.Post
13 | import com.blacklenspub.postsreader.presentation.PageNavigator
14 | import kotlinx.android.synthetic.main.activity_post_list.*
15 |
16 | class PostListActivity : LifecycleActivity() {
17 |
18 | private val TAG = "show_time"
19 |
20 | private val viewModel by lazy {
21 | ViewModelProviders.of(this).get(PostListViewModel::class.java).also {
22 | PostsReaderApplication.component.inject(it)
23 | }
24 | }
25 |
26 | private val logger = PostsReaderApplication.component.logger
27 | private val postAdapter = PostAdapter()
28 |
29 | override fun onCreate(savedInstanceState: Bundle?) {
30 | super.onCreate(savedInstanceState)
31 | logger.logDebug(TAG, "onCreate")
32 | setContentView(R.layout.activity_post_list)
33 | setupRecyclerView()
34 |
35 | getAllPosts()
36 | }
37 |
38 | override fun onDestroy() {
39 | logger.logDebug(TAG, "onDestroy")
40 | super.onDestroy()
41 | }
42 |
43 | private fun setupRecyclerView() {
44 | rvPosts.apply {
45 | setHasFixedSize(true)
46 |
47 | val linearLayoutManager = LinearLayoutManager(this@PostListActivity)
48 | layoutManager = linearLayoutManager
49 | addItemDecoration(DividerItemDecoration(context, linearLayoutManager.orientation))
50 |
51 | postAdapter.onPostClickListener = {
52 | PageNavigator.gotoPostDetailActivity(this@PostListActivity, it)
53 | }
54 | adapter = postAdapter
55 | }
56 | }
57 |
58 | private fun getAllPosts() {
59 | viewModel.getAllPosts().observe(this, Observer {
60 | if (it != null) {
61 | showPosts(it)
62 | } else {
63 | Toast.makeText(this, "What! Something went wrong.", Toast.LENGTH_SHORT).show()
64 | }
65 | })
66 | }
67 |
68 | private fun showPosts(posts: List) {
69 | postAdapter.posts = posts.sortedBy { it.id }
70 | }
71 | }
72 |
73 |
--------------------------------------------------------------------------------
/gradlew.bat:
--------------------------------------------------------------------------------
1 | @if "%DEBUG%" == "" @echo off
2 | @rem ##########################################################################
3 | @rem
4 | @rem Gradle startup script for Windows
5 | @rem
6 | @rem ##########################################################################
7 |
8 | @rem Set local scope for the variables with windows NT shell
9 | if "%OS%"=="Windows_NT" setlocal
10 |
11 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
12 | set DEFAULT_JVM_OPTS=
13 |
14 | set DIRNAME=%~dp0
15 | if "%DIRNAME%" == "" set DIRNAME=.
16 | set APP_BASE_NAME=%~n0
17 | set APP_HOME=%DIRNAME%
18 |
19 | @rem Find java.exe
20 | if defined JAVA_HOME goto findJavaFromJavaHome
21 |
22 | set JAVA_EXE=java.exe
23 | %JAVA_EXE% -version >NUL 2>&1
24 | if "%ERRORLEVEL%" == "0" goto init
25 |
26 | echo.
27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
28 | echo.
29 | echo Please set the JAVA_HOME variable in your environment to match the
30 | echo location of your Java installation.
31 |
32 | goto fail
33 |
34 | :findJavaFromJavaHome
35 | set JAVA_HOME=%JAVA_HOME:"=%
36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe
37 |
38 | if exist "%JAVA_EXE%" goto init
39 |
40 | echo.
41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
42 | echo.
43 | echo Please set the JAVA_HOME variable in your environment to match the
44 | echo location of your Java installation.
45 |
46 | goto fail
47 |
48 | :init
49 | @rem Get command-line arguments, handling Windowz variants
50 |
51 | if not "%OS%" == "Windows_NT" goto win9xME_args
52 | if "%@eval[2+2]" == "4" goto 4NT_args
53 |
54 | :win9xME_args
55 | @rem Slurp the command line arguments.
56 | set CMD_LINE_ARGS=
57 | set _SKIP=2
58 |
59 | :win9xME_args_slurp
60 | if "x%~1" == "x" goto execute
61 |
62 | set CMD_LINE_ARGS=%*
63 | goto execute
64 |
65 | :4NT_args
66 | @rem Get arguments from the 4NT Shell from JP Software
67 | set CMD_LINE_ARGS=%$
68 |
69 | :execute
70 | @rem Setup the command line
71 |
72 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
73 |
74 | @rem Execute Gradle
75 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
76 |
77 | :end
78 | @rem End local scope for the variables with windows NT shell
79 | if "%ERRORLEVEL%"=="0" goto mainEnd
80 |
81 | :fail
82 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
83 | rem the _cmd.exe /c_ return code!
84 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
85 | exit /b 1
86 |
87 | :mainEnd
88 | if "%OS%"=="Windows_NT" endlocal
89 |
90 | :omega
91 |
--------------------------------------------------------------------------------
/app/src/test/kotlin/com/blacklenspub/postsreader/presentation/postdetail/PostDetailViewModelTest.kt:
--------------------------------------------------------------------------------
1 | package com.blacklenspub.postsreader.presentation.postdetail
2 |
3 | import android.arch.core.executor.testing.InstantTaskExecutorRule
4 | import android.arch.lifecycle.MutableLiveData
5 | import android.arch.lifecycle.Observer
6 | import com.blacklenspub.postsreader.data.PostRepository
7 | import com.blacklenspub.postsreader.data.entity.Post
8 | import org.junit.Before
9 | import org.junit.Rule
10 | import org.junit.Test
11 | import org.mockito.Mock
12 | import org.mockito.Mockito.*
13 | import org.mockito.MockitoAnnotations
14 |
15 | class PostDetailViewModelTest {
16 |
17 | // we need to set this rule in order to execute LiveData operation current thread.
18 | @Rule @JvmField
19 | val instantExecutorRule = InstantTaskExecutorRule()
20 |
21 | @Mock
22 | lateinit var postRepo: PostRepository
23 |
24 | lateinit var sutViewModel: PostDetailViewModel
25 |
26 | val mockedPostId = "1"
27 | val mockedPost = Post().apply {
28 | id = mockedPostId
29 | title = "1 Title"
30 | body = "1 Body"
31 | }
32 |
33 | @Before
34 | fun setup() {
35 | MockitoAnnotations.initMocks(this)
36 | sutViewModel = PostDetailViewModel().apply { postRepo = this@PostDetailViewModelTest.postRepo }
37 | }
38 |
39 | @Test
40 | fun getPostDetail() {
41 | val repoLiveData = MutableLiveData().apply { value = mockedPost }
42 | `when`(postRepo.getPostById(mockedPostId)).thenReturn(repoLiveData)
43 | val observer = mock(Observer::class.java)
44 |
45 | sutViewModel.getPostDetail(mockedPostId).observeForever(observer as Observer)
46 |
47 | verify(postRepo).getPostById(mockedPostId)
48 | verifyNoMoreInteractions(postRepo)
49 | verify(observer).onChanged(mockedPost)
50 | verifyNoMoreInteractions(observer)
51 | }
52 |
53 | @Test
54 | fun getPostDetail_secondCalled_shouldReturnsCachedData() {
55 | val repoLiveData = MutableLiveData().apply { value = mockedPost }
56 | `when`(postRepo.getPostById(mockedPostId)).thenReturn(repoLiveData)
57 | val observer = mock(Observer::class.java)
58 |
59 | sutViewModel.getPostDetail(mockedPostId).observeForever(observer as Observer)
60 |
61 | verify(postRepo).getPostById(mockedPostId)
62 | verifyNoMoreInteractions(postRepo)
63 | verify(observer).onChanged(mockedPost)
64 | verifyNoMoreInteractions(observer)
65 |
66 | // below is the 2nd request
67 |
68 | reset(postRepo)
69 | reset(observer)
70 | sutViewModel.getPostDetail(mockedPostId)
71 |
72 | verifyNoMoreInteractions(postRepo)
73 | verifyNoMoreInteractions(observer)
74 | }
75 | }
76 |
77 |
--------------------------------------------------------------------------------
/app/src/main/kotlin/com/blacklenspub/postsreader/presentation/postdetail/PostDetailActivity.kt:
--------------------------------------------------------------------------------
1 | package com.blacklenspub.postsreader.presentation.postdetail
2 |
3 | import android.arch.lifecycle.LifecycleActivity
4 | import android.arch.lifecycle.Observer
5 | import android.arch.lifecycle.ViewModelProviders
6 | import android.content.Intent
7 | import android.os.Bundle
8 | import android.os.SystemClock
9 | import android.util.Log
10 | import android.widget.Toast
11 | import com.blacklenspub.postsreader.PostsReaderApplication
12 | import com.blacklenspub.postsreader.R
13 | import com.blacklenspub.postsreader.data.entity.Post
14 | import com.blacklenspub.postsreader.data.local.AppDatabase
15 | import kotlinx.android.synthetic.main.activity_post_detail.*
16 |
17 | class PostDetailActivity : LifecycleActivity() {
18 |
19 | private val TAG = PostDetailActivity::javaClass.name
20 |
21 | companion object {
22 | val KEY_POST_ID = "postId"
23 | }
24 |
25 | private lateinit var postId: String
26 |
27 | private val viewModel: PostDetailViewModel by lazy {
28 | ViewModelProviders.of(this).get(PostDetailViewModel::class.java).also {
29 | PostsReaderApplication.component.inject(it)
30 | }
31 | }
32 |
33 | override fun onCreate(savedInstanceState: Bundle?) {
34 | super.onCreate(savedInstanceState)
35 | setContentView(R.layout.activity_post_detail)
36 | intent?.let {
37 | retrieveIntentData(it)
38 | getPostDetail()
39 | }
40 | }
41 |
42 | private fun retrieveIntentData(data: Intent) {
43 | postId = data.getStringExtra(KEY_POST_ID)
44 | }
45 |
46 | private fun getPostDetail() {
47 | viewModel.getPostDetail(postId).observe(this, Observer {
48 | if (it != null) {
49 | setPostDetail(it)
50 | // TODO : uncomment and then observe result.
51 | // modifyPostFromOtherThread(it)
52 | } else {
53 | Log.d(TAG, "ERROR # null post data")
54 | Toast.makeText(this, "What! Something went wrong.", Toast.LENGTH_SHORT).show()
55 | }
56 | })
57 | }
58 |
59 | private fun setPostDetail(post: Post) {
60 | Log.d(TAG, "Displaying post detail for post id ${post.id}")
61 | tvPostTitle.text = post.title
62 | tvPostBody.text = post.body
63 | }
64 |
65 | // this ugly function is just for demonstration purpose.
66 | private var isPostModified = false
67 | private fun modifyPostFromOtherThread(post: Post) {
68 | if (!isPostModified) {
69 | Thread(Runnable {
70 | SystemClock.sleep(3000)
71 | post.title = "<-- Hacked by Black Lens Crew -->"
72 | post.body = "LOL : 55555"
73 | viewModel.updatePost(post)
74 | }).start()
75 | isPostModified = true
76 | }
77 | }
78 | }
79 |
80 |
--------------------------------------------------------------------------------
/app/src/test/kotlin/com/blacklenspub/postsreader/presentation/postlist/PostListViewModelTest.kt:
--------------------------------------------------------------------------------
1 | package com.blacklenspub.postsreader.presentation.postlist
2 |
3 | import android.arch.core.executor.testing.InstantTaskExecutorRule
4 | import android.arch.lifecycle.MutableLiveData
5 | import android.arch.lifecycle.Observer
6 | import com.blacklenspub.postsreader.data.PostRepository
7 | import com.blacklenspub.postsreader.data.entity.Post
8 | import com.blacklenspub.postsreader.util.Logger
9 | import org.junit.Before
10 | import org.junit.Rule
11 | import org.junit.Test
12 | import org.mockito.Mock
13 | import org.mockito.Mockito.*
14 | import org.mockito.MockitoAnnotations
15 |
16 | class PostListViewModelTest {
17 |
18 | // we need to set this rule in order to execute LiveData operation current thread.
19 | @Rule @JvmField
20 | val instantExecutorRule = InstantTaskExecutorRule()
21 |
22 | @Mock lateinit var postRepo: PostRepository
23 | @Mock lateinit var logger: Logger
24 |
25 | lateinit var sutViewModel: PostListViewModel
26 |
27 | val mockedPosts = listOf(
28 | Post().apply {
29 | id = "1"
30 | title = "1 Title"
31 | body = "1 Body"
32 | },
33 | Post().apply {
34 | id = "2"
35 | title = "2 Title"
36 | body = "2 Body"
37 | },
38 | Post().apply {
39 | id = "3"
40 | title = "3 Title"
41 | body = "3 Body"
42 | }
43 | )
44 |
45 | @Before
46 | fun setup() {
47 | MockitoAnnotations.initMocks(this)
48 | sutViewModel = PostListViewModel().apply {
49 | postRepo = this@PostListViewModelTest.postRepo
50 | logger = this@PostListViewModelTest.logger
51 | }
52 | }
53 |
54 | @Test
55 | fun getAllPosts() {
56 | val repoLiveData = MutableLiveData>().apply { value = mockedPosts }
57 | `when`(postRepo.getAllPosts()).thenReturn(repoLiveData)
58 | val observer = mock(Observer::class.java)
59 |
60 | sutViewModel.getAllPosts().observeForever(observer as Observer>)
61 |
62 | verify(postRepo).getAllPosts()
63 | verifyNoMoreInteractions(postRepo)
64 | verify(observer).onChanged(mockedPosts)
65 | verifyNoMoreInteractions(observer)
66 | }
67 |
68 | @Test
69 | fun getAllPosts_secondCalled_shouldReturnsCachedData() {
70 | val repoLiveData = MutableLiveData>().apply { value = mockedPosts }
71 | `when`(postRepo.getAllPosts()).thenReturn(repoLiveData)
72 | val observer = mock(Observer::class.java)
73 |
74 | sutViewModel.getAllPosts().observeForever(observer as Observer>)
75 |
76 | verify(postRepo).getAllPosts()
77 | verifyNoMoreInteractions(postRepo)
78 | verify(observer).onChanged(mockedPosts)
79 | verifyNoMoreInteractions(observer)
80 |
81 | // below is the 2nd request
82 |
83 | reset(postRepo)
84 | reset(observer)
85 | sutViewModel.getAllPosts()
86 |
87 | verifyNoMoreInteractions(postRepo)
88 | verifyNoMoreInteractions(observer)
89 | }
90 | }
91 |
92 |
--------------------------------------------------------------------------------
/app/src/test/kotlin/com/blacklenspub/postsreader/data/PostRepositoryImplTest.kt:
--------------------------------------------------------------------------------
1 | package com.blacklenspub.postsreader.data
2 |
3 | import android.arch.core.executor.testing.InstantTaskExecutorRule
4 | import android.arch.lifecycle.MutableLiveData
5 | import android.arch.lifecycle.Observer
6 | import com.blacklenspub.postsreader.data.entity.Post
7 | import com.blacklenspub.postsreader.data.local.PostDao
8 | import com.blacklenspub.postsreader.data.remote.PostsReaderApi
9 | import io.reactivex.Single
10 | import io.reactivex.schedulers.Schedulers
11 | import org.junit.Before
12 | import org.junit.Rule
13 | import org.junit.Test
14 | import org.mockito.Mock
15 | import org.mockito.Mockito.*
16 | import org.mockito.MockitoAnnotations
17 |
18 | class PostRepositoryImplTest {
19 |
20 | // we need to set this rule in order to execute LiveData operation current thread.
21 | @Rule @JvmField
22 | val instantExecutorRule = InstantTaskExecutorRule()
23 |
24 | @Mock
25 | lateinit var localSource: PostDao
26 | @Mock
27 | lateinit var remoteSource: PostsReaderApi
28 |
29 | lateinit var sutRepo: PostRepositoryImpl
30 |
31 | val mockedPosts = listOf(
32 | Post().apply {
33 | id = "1"
34 | title = "1 Title"
35 | body = "1 Body"
36 | },
37 | Post().apply {
38 | id = "2"
39 | title = "2 Title"
40 | body = "2 Body"
41 | },
42 | Post().apply {
43 | id = "3"
44 | title = "3 Title"
45 | body = "3 Body"
46 | }
47 | )
48 |
49 | @Before
50 | fun setup() {
51 | MockitoAnnotations.initMocks(this)
52 | sutRepo = PostRepositoryImpl(localSource, remoteSource, Schedulers.trampoline())
53 | }
54 |
55 | @Test
56 | fun getAllPosts() {
57 | `when`(remoteSource.getAllPosts()).thenReturn(Single.just(mockedPosts))
58 | `when`(localSource.getAllPosts()).thenReturn(MutableLiveData>().apply { value = mockedPosts })
59 | val observer = mock(Observer::class.java)
60 |
61 | sutRepo.getAllPosts().observeForever(observer as Observer>)
62 |
63 | verify(remoteSource).getAllPosts()
64 | verifyNoMoreInteractions(remoteSource)
65 | verify(localSource).insertOrUpdatePosts(*mockedPosts.toTypedArray())
66 | verify(localSource).getAllPosts()
67 | verifyNoMoreInteractions(localSource)
68 | verify(observer).onChanged(mockedPosts)
69 | verifyNoMoreInteractions(observer)
70 | }
71 |
72 | @Test
73 | fun getPostById() {
74 | val postId = "1"
75 | val mockedPost = mockedPosts.first { it.id == postId }
76 | `when`(remoteSource.getPostById(postId)).thenReturn(Single.just(mockedPost))
77 | `when`(localSource.getPostById(postId)).thenReturn(MutableLiveData().apply { value = mockedPost })
78 | val observer = mock(Observer::class.java)
79 |
80 | sutRepo.getPostById(postId).observeForever(observer as Observer)
81 |
82 | verify(remoteSource).getPostById(postId)
83 | verifyNoMoreInteractions(remoteSource)
84 | verify(localSource).insertOrUpdatePosts(mockedPost)
85 | verify(localSource).getPostById(postId)
86 | verifyNoMoreInteractions(localSource)
87 | verify(observer).onChanged(mockedPost)
88 | verifyNoMoreInteractions(observer)
89 | }
90 | }
91 |
92 |
--------------------------------------------------------------------------------
/gradlew:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env bash
2 |
3 | ##############################################################################
4 | ##
5 | ## Gradle start up script for UN*X
6 | ##
7 | ##############################################################################
8 |
9 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
10 | DEFAULT_JVM_OPTS=""
11 |
12 | APP_NAME="Gradle"
13 | APP_BASE_NAME=`basename "$0"`
14 |
15 | # Use the maximum available, or set MAX_FD != -1 to use that value.
16 | MAX_FD="maximum"
17 |
18 | warn ( ) {
19 | echo "$*"
20 | }
21 |
22 | die ( ) {
23 | echo
24 | echo "$*"
25 | echo
26 | exit 1
27 | }
28 |
29 | # OS specific support (must be 'true' or 'false').
30 | cygwin=false
31 | msys=false
32 | darwin=false
33 | case "`uname`" in
34 | CYGWIN* )
35 | cygwin=true
36 | ;;
37 | Darwin* )
38 | darwin=true
39 | ;;
40 | MINGW* )
41 | msys=true
42 | ;;
43 | esac
44 |
45 | # Attempt to set APP_HOME
46 | # Resolve links: $0 may be a link
47 | PRG="$0"
48 | # Need this for relative symlinks.
49 | while [ -h "$PRG" ] ; do
50 | ls=`ls -ld "$PRG"`
51 | link=`expr "$ls" : '.*-> \(.*\)$'`
52 | if expr "$link" : '/.*' > /dev/null; then
53 | PRG="$link"
54 | else
55 | PRG=`dirname "$PRG"`"/$link"
56 | fi
57 | done
58 | SAVED="`pwd`"
59 | cd "`dirname \"$PRG\"`/" >/dev/null
60 | APP_HOME="`pwd -P`"
61 | cd "$SAVED" >/dev/null
62 |
63 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
64 |
65 | # Determine the Java command to use to start the JVM.
66 | if [ -n "$JAVA_HOME" ] ; then
67 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
68 | # IBM's JDK on AIX uses strange locations for the executables
69 | JAVACMD="$JAVA_HOME/jre/sh/java"
70 | else
71 | JAVACMD="$JAVA_HOME/bin/java"
72 | fi
73 | if [ ! -x "$JAVACMD" ] ; then
74 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
75 |
76 | Please set the JAVA_HOME variable in your environment to match the
77 | location of your Java installation."
78 | fi
79 | else
80 | JAVACMD="java"
81 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
82 |
83 | Please set the JAVA_HOME variable in your environment to match the
84 | location of your Java installation."
85 | fi
86 |
87 | # Increase the maximum file descriptors if we can.
88 | if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then
89 | MAX_FD_LIMIT=`ulimit -H -n`
90 | if [ $? -eq 0 ] ; then
91 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
92 | MAX_FD="$MAX_FD_LIMIT"
93 | fi
94 | ulimit -n $MAX_FD
95 | if [ $? -ne 0 ] ; then
96 | warn "Could not set maximum file descriptor limit: $MAX_FD"
97 | fi
98 | else
99 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
100 | fi
101 | fi
102 |
103 | # For Darwin, add options to specify how the application appears in the dock
104 | if $darwin; then
105 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
106 | fi
107 |
108 | # For Cygwin, switch paths to Windows format before running java
109 | if $cygwin ; then
110 | APP_HOME=`cygpath --path --mixed "$APP_HOME"`
111 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
112 | JAVACMD=`cygpath --unix "$JAVACMD"`
113 |
114 | # We build the pattern for arguments to be converted via cygpath
115 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
116 | SEP=""
117 | for dir in $ROOTDIRSRAW ; do
118 | ROOTDIRS="$ROOTDIRS$SEP$dir"
119 | SEP="|"
120 | done
121 | OURCYGPATTERN="(^($ROOTDIRS))"
122 | # Add a user-defined pattern to the cygpath arguments
123 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then
124 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
125 | fi
126 | # Now convert the arguments - kludge to limit ourselves to /bin/sh
127 | i=0
128 | for arg in "$@" ; do
129 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
130 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
131 |
132 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
133 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
134 | else
135 | eval `echo args$i`="\"$arg\""
136 | fi
137 | i=$((i+1))
138 | done
139 | case $i in
140 | (0) set -- ;;
141 | (1) set -- "$args0" ;;
142 | (2) set -- "$args0" "$args1" ;;
143 | (3) set -- "$args0" "$args1" "$args2" ;;
144 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;;
145 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
146 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
147 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
148 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
149 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
150 | esac
151 | fi
152 |
153 | # Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules
154 | function splitJvmOpts() {
155 | JVM_OPTS=("$@")
156 | }
157 | eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS
158 | JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME"
159 |
160 | exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@"
161 |
--------------------------------------------------------------------------------