All Downloads are FREE. Search and download functionalities are using the official Maven repository.

jvmMain.com.pubnub.api.endpoints.remoteaction.MappingRemoteAction.kt Maven / Gradle / Ivy

Go to download

PubNub is a cross-platform client-to-client (1:1 and 1:many) push service in the cloud, capable of broadcasting real-time messages to millions of web and mobile clients simultaneously, in less than a quarter second!

The newest version!
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)
}