You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为何NotificationCenter+Rx属于RxCocoa而非RxSwift?

Why is NotificationCenter+Rx in RxCocoa instead of RxSwift?

Great question—this is a common point of confusion since NotificationCenter lives in Foundation, not UIKit/AppKit. Let’s break this down clearly:

The Core Split Between RxSwift and RxCocoa

First, let’s recap the fundamental roles of these two frameworks:

  • RxSwift: This is the lightweight, platform-agnostic core of the reactive toolkit. It handles all the basic reactive primitives like Observable, Observer, operators, and scheduling—with no ties to Apple’s Cocoa/CocoaTouch frameworks. It’s designed to be usable even outside Apple ecosystems, though most developers use it alongside Apple platforms.
  • RxCocoa: This layer bridges RxSwift to Apple’s native frameworks. Its sole job is to wrap Cocoa/CocoaTouch APIs (including parts of Foundation deeply tied to platform behavior) into reactive extensions. That includes UIKit controls, AppKit components, and yes—NotificationCenter.

Why NotificationCenter Lands in RxCocoa

Even though NotificationCenter is part of Foundation, its most common use cases on Apple platforms are tightly coupled to Cocoa/CocoaTouch workflows:

  • Listening to system notifications like UIApplication.didEnterBackgroundNotification or UIResponder.keyboardWillShowNotification
  • Observing app-specific events tied to UI state changes
  • Integrating with other Cocoa framework components that rely on notifications for communication

RxCocoa is home to all these platform-specific reactive bindings. Keeping NotificationCenter+Rx here keeps RxSwift clean, focused solely on core reactive logic without platform dependencies.

Fixing Your Error

If your project only uses RxSwift and can’t add RxCocoa, you can easily implement a minimal version of this extension yourself using RxSwift’s core APIs:

import RxSwift
import Foundation

extension Reactive where Base: NotificationCenter {
    func notification(_ name: Notification.Name, object: AnyObject? = nil) -> Observable<Notification> {
        return Observable.create { observer in
            // Add the notification observer
            let observerToken = self.base.addObserver(
                forName: name,
                object: object,
                queue: nil
            ) { notification in
                observer.onNext(notification)
            }
            
            // Return a disposable to clean up the observer when done
            return Disposables.create {
                self.base.removeObserver(observerToken)
            }
        }
    }
}

Drop this extension into your codebase, and NotificationCenter.default.rx.notification() will work just like the RxCocoa version.

内容的提问来源于stack exchange,提问作者Jake Lin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 09:34:53