下面的代码运行良好。
资源
sealed class Resource<out T:Any>{
data class Success<out T:Any> (val data:T):Resource<T>()
data class Error(val exception: Exception):Resource<Nothing>()
data class Loading(val message:String):Resource<Nothing>()
}
流程结构
fun simple(): Flow<Resource<String>> = flow {
delay(100)
emit(Resource.Loading("Loading message..."))
delay(100)
emit(Resource.Error(Exception("Error Message")))
delay(100)
emit(Resource.Success("Value=X"))
}
suspend fun <T> Flow<T>.process(
onLoading: ((T)->Unit),
onError: ((T)->Unit),
onSuccess: ((T)->Unit)) {
collect { value ->
when ( value ) {
is Resource.Error -> {
onError(value)
}
is Resource.Loading -> {
onLoading(value)
}
is Resource.Success<*> -> {
onSuccess(value)
}
}
}
}
fun job1() {
viewModelScope.launch {
simple().process({
}, {
}, {
})
}
}
如图所示,所有回调都返回Resource<String>
类型。是否可以为onLoading
回调返回Resource.Loading
,为onError
回调返回Resource.Error
,为onSuccess
回调返回Resource.Success<String>
?
我想达到的是:
fun job1() {
viewModelScope.launch {
simple().process({Resource.Loading
}, {Resource.Error
}, {Resource.Success<String>
})
}
}
另一个问题是编译器强迫我写Resource.Success<*>
.否则给出错误:这样写有什么坏处吗?
编辑_1:
suspend fun <T: Resource<Any>> Flow<T>.process(
onLoading: ((Resource.Loading)->Unit),
onError: ((Resource.Error)->Unit),
onSuccess: ((T)->Unit)) {
collect { value ->
when ( value ) {
is Resource.Error -> {
onError(value)
}
is Resource.Loading -> {
onLoading(value)
}
is Resource.Success<*> -> {
onSuccess(value)
}
}
}
}
编辑_2
我能做的最好的,但给出错误:
如果我强制转换为。。
2条答案
按热度按时间bvjxkvbb1#
如果我理解正确的话,你需要把你的
process
方法改为https://pl.kotl.in/Ho_gw0q31
但是如果你想返回整个
onSuccess
,你可以这样做xsuvu9jc2#
你的意思是: