Android-使用流创建回调
我试图理解流程,但几乎没有什么事情是我不清楚的。我有一个简单的界面:Android-使用流创建回调,android,kotlin-coroutines,kotlin-flow,Android,Kotlin Coroutines,Kotlin Flow,我试图理解流程,但几乎没有什么事情是我不清楚的。我有一个简单的界面: interface Operation<T> { fun performAsync(callback: (T? , Throwable?) -> Unit) fun cancel() } 请您解释一下,如何观察异常(或T值)并在Activity/Fragment中发送/接收异常?您如何使用密封类 sealed class Operation<out V, out E> { da
interface Operation<T> {
fun performAsync(callback: (T? , Throwable?) -> Unit)
fun cancel()
}
请您解释一下,如何观察异常(或T值)并在Activity/Fragment中发送/接收异常?您如何使用密封类
sealed class Operation<out V, out E> {
data class Result<out V> (val data: V) : Operation<V, Nothing>()
data class Error<out E> (val error: E) : Operation<Nothing, E>()
companion object {
inline fun <V> build(operation : () -> V) : Response<V, Exception> {
return try {
Value(operation.invoke())
} catch (e: Exception) {
Error(e)
}
}
}
fun convert () {
try {
val carJSON = gson.toJson(carObj)
//send Car value
} catch (e : Exception) {
//here I want to send exception and receive it in callback in activity/fragment.
}
}
sealed class Operation<out V, out E> {
data class Result<out V> (val data: V) : Operation<V, Nothing>()
data class Error<out E> (val error: E) : Operation<Nothing, E>()
companion object {
inline fun <V> build(operation : () -> V) : Response<V, Exception> {
return try {
Value(operation.invoke())
} catch (e: Exception) {
Error(e)
}
}
}
fun someFunction() : Operation<Flow<String>, Exception> {
val flow = callbackFlow<String> {
val callback = object : someCallback {
onResult(result: String) {
offer(result)
}
onError(e: Exception) {
throw e
}
}
awaitClose { callback.remove() } //Just an example of a callback
}
return Operation.build { flow }
}
when(someFunction) {
is Operation.Result -> collect(someFunction().data)
is Operation.Error -> handleErrorAsHoweverYouWant(someFunction().error)
}