我是Kotlin泛型新手,这里我尝试声明MutableSharedFlow<EventFilter<T>>()
的泛型变量
我尝试了这个,但是在var <T>
上显示错误
var <T> event = MutableSharedFlow<EventFilter<T>>()
^
Error :Type parameter of a property must be used in its receiver type
我不明白这个错误任何一个指南如何声明这一个在通用的方式。
enum class EventType {
DEFAULT,
ADD_PLAY_LIST,
PLAY_PAUSE,
STOP
}
data class EventFilter<T>(var eventType: EventType = EventType.DEFAULT, var anyObject: T? = null)
var <T> events: MutableSharedFlow<EventFilter<T>> = MutableSharedFlow<EventFilter<T>>()
fun <T> receivedEventX(filter: EventFilter<T> = EventFilter(), onReceivedEvent: (event: EventFilter<T>) -> Unit) {
CoroutineScope(Dispatchers.Main).launch {
events.collectLatest {
onReceivedEvent.invoke(it)
}
}
}
fun <T> sendEventX(event: EventFilter<T> = EventFilter()) {
CoroutineScope(Dispatchers.Main).launch {
events.emit(event)
}
}
1条答案
按热度按时间yyhrrdl81#
要声明一个
MutableSharedFlow
可以用途:val flow: MutableSharedFlow<EventFilter<T>> = MutableSharedFlow()
默认类型为
Any?
。并将其与一个特殊类型一起使用:
val thisFlow: MutableSharedFlow<EventFilter<String>> = MutableSharedFlow()