Created
October 21, 2018 10:05
-
-
Save Abhityagi16/0cdd043de30a467d43db624bdfc3710b to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import clean.architecture.example.data.model.Post | |
class PostDataRepository private constructor( | |
private val localDataSource: PostDataSource, | |
private val remoteDataSource: PostDataSource): PostDataSource { | |
companion object { | |
private var INSTANCE: PostDataRepository? = null | |
fun getInstance(localDataSource: PostDataSource, remoteDataSource: PostDataSource): PostDataRepository { | |
if (INSTANCE == null) { | |
INSTANCE = PostDataRepository(localDataSource, remoteDataSource) | |
} | |
return INSTANCE!! | |
} | |
} | |
var isCacheDirty = false | |
override fun getPosts(userId: Int, callback: PostDataSource.LoadPostsCallback) { | |
if (isCacheDirty) { | |
getPostsFromServer(userId, callback) | |
} else { | |
localDataSource.getPosts(userId, object : PostDataSource.LoadPostsCallback { | |
override fun onPostsLoaded(posts: List<Post>) { | |
refreshCache() | |
callback.onPostsLoaded(posts) | |
} | |
override fun onError(t: Throwable) { | |
getPostsFromServer(userId, callback) | |
} | |
}) | |
} | |
} | |
override fun savePost(post: Post) { | |
localDataSource.savePost(post) | |
remoteDataSource.savePost(post) | |
} | |
private fun getPostsFromServer(userId: Int, callback: PostDataSource.LoadPostsCallback) { | |
remoteDataSource.getPosts(userId, object : PostDataSource.LoadPostsCallback { | |
override fun onPostsLoaded(posts: List<Post>) { | |
refreshCache() | |
refreshLocalDataSource(posts) | |
callback.onPostsLoaded(posts) | |
} | |
override fun onError(t: Throwable) { | |
callback.onError(t) | |
} | |
}) | |
} | |
private fun refreshLocalDataSource(posts: List<Post>) { | |
posts.forEach { | |
localDataSource.savePost(it) | |
} | |
} | |
private fun refreshCache() { | |
isCacheDirty = false | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
interface PostDataSource { | |
interface LoadPostsCallback { | |
fun onPostsLoaded(posts: List<Post>) | |
fun onError(t: Throwable) | |
} | |
fun getPosts(userId: Int, callback: LoadPostsCallback) | |
fun savePost(post: Post) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment