Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Sample snippet for a canonical problem resolved using RxJava
interface DataSource {
fun allTasksByUser(user: User): Observable<List<Task>>
}
class LocalDataSource : DataSource {
private val localCache: Map<User, List<Task>> =
mapOf(User(UserId("user1")) to listOf(Task("LocalTask assigned to user1")))
override fun allTasksByUser(user: User): Observable<List<Task>> = Observable.create { emitter ->
val cachedUser = localCache[user]
if (cachedUser != null) {
emitter.onNext(cachedUser)
} else {
emitter.onError(UserNotInLocalStorage(user))
}
}
}
class RemoteDataSource : DataSource {
private val internetStorage: Map<User, List<Task>> =
mapOf(User(UserId("user2")) to listOf(Task("Remote Task assigned to user2")))
override fun allTasksByUser(user: User): Observable<List<Task>> = Observable.create { emitter ->
val networkUser = internetStorage[user]
if (networkUser != null) {
emitter.onNext(networkUser)
} else {
emitter.onError(UserNotInRemoteStorage(user))
}
}
}
class TaskRepository(private val localDS: DataSource, private val remoteDS: RemoteDataSource) {
fun allTasksByUser(user: User): Observable<List<Task>> =
localDS.allTasksByUser(user)
.subscribeOn(Schedulers.io())
.observeOn(Schedulers.computation())
.onErrorResumeNext { _: Throwable -> remoteDS.allTasksByUser(user) }
}
class Module {
private val localDataSource: LocalDataSource = LocalDataSource()
private val remoteDataSource: RemoteDataSource = RemoteDataSource()
val repository: TaskRepository = TaskRepository(localDataSource, remoteDataSource)
}
object test {
@JvmStatic
fun main(args: Array<String>): Unit {
val user1 = User(UserId("user1"))
val user2 = User(UserId("user2"))
val user3 = User(UserId("unknown user"))
val dependenciesModule = Module()
dependenciesModule.run {
repository.allTasksByUser(user1).subscribe({ println(it) }, { println(it) })
repository.allTasksByUser(user2).subscribe({ println(it) }, { println(it) })
repository.allTasksByUser(user3).subscribe({ println(it) }, { println(it) })
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.