Skip to content

Instantly share code, notes, and snippets.

@IanField90
Created November 22, 2018 16:56
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 IanField90/50744657a77260cc56455ac95e0be3e3 to your computer and use it in GitHub Desktop.
Save IanField90/50744657a77260cc56455ac95e0be3e3 to your computer and use it in GitHub Desktop.
Kotlin Mockito Rx Callback
/**
* Helper functions that are workarounds to kotlin Runtime Exceptions when using kotlin.
*/
import org.mockito.ArgumentCaptor
import org.mockito.Mockito
/**
* Returns Mockito.eq() as nullable type to avoid java.lang.IllegalStateException when
* null is returned.
*
* Generic T is nullable because implicitly bounded by Any?.
*/
fun <T> eq(obj: T): T = Mockito.eq<T>(obj)
/**
* Returns Mockito.any() as nullable type to avoid java.lang.IllegalStateException when
* null is returned.
*/
fun <T> any(): T = Mockito.any<T>()
/**
* Returns ArgumentCaptor.capture() as nullable type to avoid java.lang.IllegalStateException
* when null is returned.
*/
fun <T> capture(argumentCaptor: ArgumentCaptor<T>): T = argumentCaptor.capture()
/**
* Helper function for creating an argumentCaptor in kotlin.
*/
inline fun <reified T : Any> argumentCaptor(): ArgumentCaptor<T> =
ArgumentCaptor.forClass(T::class.java)
inline fun <reified T : Any> mockInline() = Mockito.mock(T::class.java)
val callback = object : SnapshotCallback<SnapshotResponse> {
override fun success(data: SnapshotResponse?) {
if (data != null) {
view.setSnapshot(data)
}
view.hideProgress()
}
override fun error(error: SnapshotError) {
view.hideProgress()
view.showError()
}
}
lateinit var callback: SnapshotCallback<SnapshotResponse>
Single.create { emitter: SingleEmitter<SnapshotResponse> ->
callback = object : SnapshotCallback<SnapshotResponse> {
override fun success(data: SnapshotResponse?) {
data?.let { emitter.onSuccess(data) }
}
override fun error(error: SnapshotError) {
emitter.onError(error)
}
}
}.observeOn(ioScheduler)
.subscribeOn(uiScheduler)
.doOnSuccess { result ->
view.hideProgress()
view.setSnapshot(result)
}
.doOnError {
view.hideProgress()
view.showError()
}
.subscribe()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment