Skip to content

Instantly share code, notes, and snippets.

@houssemzaier
Created July 26, 2018 21:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save houssemzaier/e03ed12ee4f8f5a482f3d24ca12a3cef to your computer and use it in GitHub Desktop.
Save houssemzaier/e03ed12ee4f8f5a482f3d24ca12a3cef to your computer and use it in GitHub Desktop.
This sample shows replayed response (that could have a param) from an Observable Subject used like a proxy between the client and original Observable
import io.reactivex.Observable
import io.reactivex.subjects.PublishSubject
import java.util.*
fun main(args: Array<String>) {
val vm = VM(Repo())
vm.observableData.subscribe {
println("from sub1 $it")
}
Thread.sleep(3333)
vm.observableData.subscribe {
println("from sub2 $it")
}
vm.requestData("JayZeeBra")
Thread.sleep(3333)
vm.observableData.subscribe {
println("from sub3 $it")
}
}
class VM(repo: Repo) {
private val subject: PublishSubject<String> = PublishSubject.create()
var observableData: Observable<String>
init {
observableData = subject.flatMap {
repo.fetchDataFromInfrastructure(it)
}.replay().autoConnect()
}
fun requestData(nameOfRequester: String) {
subject.onNext(nameOfRequester)
}
}
class Repo {
fun fetchDataFromInfrastructure(caller: String? = null): Observable<String> =
Observable.fromIterable(listOf(1, 2, 3, 4, 5))
.map { number ->
"from caller: $caller ===> $number " + (0..100).random()
}
}
fun ClosedRange<Int>.random() =
Random().nextInt((endInclusive + 1) - start) + start
@houssemzaier
Copy link
Author

sub1 ,sub2 and sub3 get the same result as it is cached using the replay() , helpful in some cases

@houssemzaier
Copy link
Author

autoConnect() maybe that 's not the best choice , I'd prefere to use autoConnect(1, addTo(disposible))

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment