Last active
July 21, 2017 15:43
-
-
Save DarrenAtherton49/20cbbf3a49ce1d2c8a5cabe699cd18ad to your computer and use it in GitHub Desktop.
Parameterised reactive use cases in Kotlin
This file contains 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
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) | |
} | |
} |
This file contains 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
getPosts.execute( | |
onNext = { it.forEach { Log.d("darren", it.selftext) } }, | |
onError = { Log.d("darren", it.message )}, | |
onCompleted = { Log.d("darren", "onCompleted") } | |
) |
This file contains 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
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