我正在尝试理解 Flow,但对我来说几乎没有什么不清楚的。我有一个简单的界面:
interface Operation<T> {
fun performAsync(callback: (T? , Throwable?) -> Unit)
fun cancel()
}
然后我有一个具有功能的管理器类:
fun<T : Any> Operation<T>.perform(): Flow<T> =
callbackFlow {
performAsync {
value , exception ->
when {
exception !=null -> close(exception) //operation had failed
value == null -> close() //operation had succeeded
else -> offer(value as T)
}
}
awaitClose { cancel() }
}
假设我有一个非常简单的操作 - 尝试使用 gson 将对象序列化为 JSON:
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.
}
}
请您解释一下,如何观察异常(或 T 值)并在 Activity/Fragment 中发送/接收它?