com.pubnub.api.endpoints.remoteaction.MappingRemoteAction.kt Maven / Gradle / Ivy
package com.pubnub.api.endpoints.remoteaction
import com.pubnub.api.PubNubException
import com.pubnub.api.enums.PNOperationType
import com.pubnub.api.v2.callbacks.Result
import java.util.function.Consumer
class MappingRemoteAction(private val remoteAction: ExtendedRemoteAction, private val function: (T) -> U) :
ExtendedRemoteAction {
override fun operationType(): PNOperationType {
return remoteAction.operationType()
}
override fun retry() {
remoteAction.retry()
}
override fun sync(): U = function(remoteAction.sync())
override fun silentCancel() {
remoteAction.silentCancel()
}
override fun async(callback: Consumer>) {
remoteAction.async { r ->
r.onSuccess {
val newValue =
try {
function(it)
} catch (e: Throwable) {
callback.accept(Result.failure(PubNubException.from(e)))
return@onSuccess
}
callback.accept(Result.success(newValue))
}.onFailure {
callback.accept(Result.failure(it.copy(remoteAction = this)))
}
}
}
}
fun ExtendedRemoteAction.map(function: (T) -> U): ExtendedRemoteAction {
return MappingRemoteAction(this, function)
}