简体   繁体   English

Kotlin 协程中是否有 RxJava 主题的类似物?

[英]Is there analogue for RxJava Subject in Kotlin Coroutines?

In 2020 a lot of android developers are talking about Kotlin Coroutines. 2020 年,很多安卓开发者都在谈论 Kotlin 协程。 I'm trying to understand it and how coroutines can help me in my project.我试图理解它以及协程如何在我的项目中帮助我。

So my question: is there analogue in Coroutines for RxJava Subjects?所以我的问题RxJava 主题的协程中是否有类似的东西? (As minimum for PublishSubject ). (作为PublishSubject最低要求)。

What I want - I use PublishSubject for sending events from ViewModel to my View .我想要什么 - 我使用PublishSubject将事件从ViewModel发送到我的View I subscribe to eventsSubject on onStart() method and dispose on onStop() method.我在onStart()方法上订阅 eventsSubject 并在onStop()方法上处理。

So the minimal requirements for Kotlin Coroutines analogue are:所以 Kotlin Coroutines 模拟的最低要求是:

  • Easy testing (I use TestSubscriber and it is awesome)易于测试(我使用 TestSubscriber,它很棒)
  • I want to send events without buffering我想在没有缓冲的情况下发送事件
  • Easy to subscribe/unsubscribe易于订阅/取消订阅

There is sample of my use case:有我的用例示例:

ViewModel:视图模型:

abstract class AbsStateViewModel<State, Event> : AbsViewModel() {
    private val stateSubject = BehaviorSubject.create<State>()
    private val eventSubject = PublishSubject.create<Event>()

    protected val requireState: State
        get() = stateSubject.value!!

    fun getStateObservable(): Observable<State> = stateSubject

    fun getEventObservable(): Observable<Event> = eventSubject

    protected fun sendEvent(event: Event) {
        eventSubject.onNext(event)
    }

    protected fun setState(state: State) {
        stateSubject.onNext(state)
    }
}

And usages:和用法:

viewModel.getEventObservable() // called on onAttach()
            .subscribe(
                    this::handleEvent,
                    this::defaultHandleException
            )
            .disposeOnDetach() // my extensions 

yes in coroutines there are the analogue of rx subjects, the channels.是的,在协程中有 rx 主题的类似物,即通道。 If you want to reproduce the behavior of PublishSubject you can use the BroadcastChannel else if you want to reproduce the behavior of BehaviorSubject you can use the ConflatedBroadcastChannel .如果您想重现PublishSubject的行为,您可以使用BroadcastChannel否则,如果您想重现BehaviorSubject的行为,您可以使用ConflatedBroadcastChannel

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM