Skip to content

Instantly share code, notes, and snippets.

@DarrenAtherton49
Last active July 21, 2017 15:43
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save DarrenAtherton49/20cbbf3a49ce1d2c8a5cabe699cd18ad to your computer and use it in GitHub Desktop.
Save DarrenAtherton49/20cbbf3a49ce1d2c8a5cabe699cd18ad to your computer and use it in GitHub Desktop.
Parameterised reactive use cases in Kotlin
class GetPosts @Inject constructor(
uiExecutor: UiExecutor,
@Named("ioExecutor") backgroundExecutor: BackgroundExecutor,
private val redditRepository: RedditRepository
) : ReactiveUseCase<List<RedditLink>>(uiExecutor, backgroundExecutor) {
fun execute(onNext: (List<RedditLink>) -> Unit,
onError: (Throwable) -> Unit,
onCompleted: () -> Unit) {
super.executeUseCase(onNext, onError, onCompleted)
}
override fun useCaseObservable(): Observable<List<RedditLink>> {
val subreddit = Subreddit.ANDROIDDEV
val filterType = RedditFilterType.HOT
return redditRepository.getLinksForSubreddit(subreddit, filterType)
}
}
getPosts.execute(
onNext = { it.forEach { Log.d("darren", it.selftext) } },
onError = { Log.d("darren", it.message )},
onCompleted = { Log.d("darren", "onCompleted") }
)
abstract class ReactiveUseCase<ObservableType> (
private val uiExecutor: UiExecutor,
private val backgroundExecutor: BackgroundExecutor) {
private var subscription = Subscriptions.empty()
protected fun executeUseCase(onNext: (ObservableType) -> Unit = {},
onError: (Throwable) -> Unit = {},
onCompleted: () -> Unit = {}) {
this.subscription = useCaseObservable()
.subscribeOn(backgroundExecutor.scheduler)
.observeOn(uiExecutor.scheduler)
.subscribe(onNext, onError, onCompleted)
}
protected abstract fun useCaseObservable(): Observable<ObservableType>
fun unsubscribe() {
if (!subscription.isUnsubscribed) {
subscription.unsubscribe()
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment