android 如何在Kotlin中声明MutableSharedFlow〈EventFilter>()的泛型变量< T>

zdwk9cvp  于 2022-12-09  发布在  Android
关注(0)|答案(1)|浏览(149)

我是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)
    }
}
yyhrrdl8

yyhrrdl81#

要声明一个MutableSharedFlow可以用途:
val flow: MutableSharedFlow<EventFilter<T>> = MutableSharedFlow()
默认类型为Any?
并将其与一个特殊类型一起使用:
val thisFlow: MutableSharedFlow<EventFilter<String>> = MutableSharedFlow()

相关问题