Skip to content

Instantly share code, notes, and snippets.

package clean.architecture.example.utils
import android.arch.lifecycle.ViewModel
import android.arch.lifecycle.ViewModelProvider
import clean.architecture.example.postlist.PostListViewModel
class ViewModelFactory : ViewModelProvider.Factory {
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
import clean.architecture.example.data.model.Post
interface PostDataSource {
interface LoadPostsCallback {
fun onPostsLoaded(posts: List<Post>)
fun onError(t: Throwable)
}
interface SaveTaskCallback {
import clean.architecture.example.UseCase
import clean.architecture.example.data.model.Post
import clean.architecture.example.data.source.PostDataRepository
import clean.architecture.example.data.source.PostDataSource
class GetPosts(private val mDataRepository: PostDataRepository) : UseCase<GetPosts.RequestValues, GetPosts.ResponseValue>() {
protected override fun executeUseCase(requestValues: GetPosts.RequestValues?) {
mDataRepository.getPosts(requestValues?.userId ?: -1, object : PostDataSource.LoadPostsCallback {
override fun onPostsLoaded(posts: List<Post>) {
class PostListViewModel(
val useCaseHandler: UseCaseHandler,
val getposts: GetPosts,
val savePost: SavePost): ViewModel() {
fun getAllPosts(userId: Int, callback: PostDataSource.LoadPostsCallback) {
val requestValue = GetPosts.RequestValues(userId)
useCaseHandler.execute(getposts, requestValue, object : UseCase.UseCaseCallback<GetPosts.ResponseValue> {
override fun onSuccess(response: GetPosts.ResponseValue) {
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
interface UseCaseScheduler {
fun execute(runnable: Runnable)
fun <V : UseCase.ResponseValue> notifyResponse(response: V,
useCaseCallback: UseCase.UseCaseCallback<V>)
fun <V : UseCase.ResponseValue> onError(
useCaseCallback: UseCase.UseCaseCallback<V>, t: Throwable)
}
class UseCaseHandler(private val mUseCaseScheduler: UseCaseScheduler) {
fun <T : UseCase.RequestValues, R : UseCase.ResponseValue> execute(
useCase: UseCase<T, R>, values: T, callback: UseCase.UseCaseCallback<R>) {
useCase.requestValues = values
useCase.useCaseCallback = UiCallbackWrapper(callback, this)
mUseCaseScheduler.execute(Runnable {
useCase.run()
})
abstract class UseCase<Q : UseCase.RequestValues, P : UseCase.ResponseValue> {
var requestValues: Q? = null
var useCaseCallback: UseCaseCallback<P>? = null
internal fun run() {
executeUseCase(requestValues)
}