Last active
August 12, 2019 06:51
-
-
Save mbiamont/002f82b0800b08ffccb6e3f31057537a to your computer and use it in GitHub Desktop.
Function to use synchronously a function returning its value by a lambda
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
package com.github.gist.mbiamont | |
import kotlinx.coroutines.runBlocking | |
import kotlin.coroutines.resume | |
import kotlin.coroutines.resumeWithException | |
import kotlin.coroutines.suspendCoroutine | |
inline fun <T> resynchronize(crossinline block: (onSuccess: (result: T) -> Unit, onError: (e: Throwable) -> Unit) -> Unit): T { | |
return runBlocking { | |
suspendCoroutine<T> { continuation -> | |
block.invoke({ result -> | |
continuation.resume(result) | |
}, { e -> | |
continuation.resumeWithException(e) | |
}) | |
} | |
} | |
} | |
inline fun <T> resynchronize(crossinline block: (onSuccess: (result: T) -> Unit) -> Unit): T { | |
return runBlocking { | |
suspendCoroutine<T> { continuation -> | |
block.invoke { result -> | |
continuation.resume(result) | |
} | |
} | |
} | |
} | |
inline fun <T, V> resynchronize(p1: V, crossinline block: (p1: V, onSuccess: (result: T) -> Unit) -> Unit): T { | |
return runBlocking { | |
suspendCoroutine<T> { continuation -> | |
block.invoke(p1) { result -> | |
continuation.resume(result) | |
} | |
} | |
} | |
} | |
inline fun <T, V> resynchronize( | |
p1: V, | |
crossinline block: (p1: V, onSuccess: (result: T) -> Unit, onError: (e: Throwable) -> Unit) -> Unit | |
): T { | |
return runBlocking { | |
suspendCoroutine<T> { continuation -> | |
block.invoke(p1, { result -> | |
continuation.resume(result) | |
}, { e -> | |
continuation.resumeWithException(e) | |
}) | |
} | |
} | |
} |
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
package com.github.gist.mbiamont | |
class UserRepository( | |
private val localUserService: ILocalUserService | |
) : UserDataSource { | |
fun getAccessToken() : String = resynchronize(::getAccessTokenAsync) | |
private fun getAccessTokenAsync(onSuccess: (accessToken: String) -> Unit, onError: (e: Throwable) -> Unit) = | |
localUserService.getUserAccessToken(onSuccess, onError) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment