生活随笔
收集整理的這篇文章主要介紹了
RxSwift之NotificationCenter的使用和自定义
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
一、系統(tǒng)通知的注冊與響應(yīng)
① 監(jiān)聽?wèi)?yīng)用進(jìn)入后臺的通知
- 現(xiàn)有如下需求:程序編譯運(yùn)行后,當(dāng)按下設(shè)備的 home 鍵,程序進(jìn)入后臺的同時會在控制臺中輸出相關(guān)信息。
- 程序進(jìn)入后臺時除了會執(zhí)行 AppDelegate.swift 里的 applicationDidEnterBackground 方法外,還會發(fā)送 UIApplicationDidEnterBackground 通知,這里可以使用 NotificationCenter 的 Rx 擴(kuò)展方法來監(jiān)聽這個通知。
- 關(guān)于 .takeUntil(self.rx.deallocated):它的作用是保證頁面銷毀的時候自動移除通知注冊,避免內(nèi)存浪費(fèi)或出現(xiàn)奔潰。
_ = NotificationCenter.default.rx
.notification(NSNotification.Name.UIApplicationDidEnterBackground).takeUntil(self.rx
.deallocated
) .subscribe(onNext
: { _ inprint("程序進(jìn)入到后臺")})
程序進(jìn)入到后臺
② 監(jiān)聽鍵盤的通知
- 分別監(jiān)聽虛擬鍵盤的打開和關(guān)閉通知,并在控制臺中輸出相關(guān)信息:
let textField
= UITextField(frame
: CGRect(x
:20, y
:100, width
:200, height
:30))
textField
.borderStyle
= .roundedRect
textField
.returnKeyType
= .done
self.view
.addSubview(textField
)
textField
.rx
.controlEvent(.editingDidEndOnExit
).subscribe(onNext
: { _ intextField
.resignFirstResponder()}).disposed(by
: disposeBag
)
_ = NotificationCenter.default.rx
.notification(NSNotification.Name.UIKeyboardWillShow).takeUntil(self.rx
.deallocated
) .subscribe(onNext
: { _ inprint("鍵盤出現(xiàn)")})
_ = NotificationCenter.default.rx
.notification(NSNotification.Name.UIKeyboardWillHide).takeUntil(self.rx
.deallocated
) .subscribe(onNext
: { _ inprint("鍵盤消失")})
二、自定義通知的發(fā)送與接收
- 定義一個 MyObserver.swift(觀察者在收到通知后的執(zhí)行的處理函數(shù)中,添加了個 3 秒的等待),如下:
class MyObserver: NSObject {var name
:String = ""init(name
:String){super.init()self.name
= name
let notificationName
= Notification.Name(rawValue
: "DownloadImageNotification")_ = NotificationCenter.default.rx
.notification(notificationName
).takeUntil(self.rx
.deallocated
) .subscribe(onNext
: { notification
inlet userInfo
= notification
.userInfo
as! [String: AnyObject]let value1
= userInfo
["value1"] as! Stringlet value2
= userInfo
["value2"] as! Intprint("\(name) 獲取到通知,用戶數(shù)據(jù)是[\(value1),\(value2)]")sleep(3)print("\(name) 執(zhí)行完畢")})}
}
- 發(fā)出一個攜帶有自定義數(shù)據(jù)的通知,同時創(chuàng)建兩個觀察者來接收這個通知:
let observers
= [MyObserver(name
: "觀察器1"),MyObserver(name
: "觀察器2")]print("發(fā)送通知")
let notificationName
= Notification.Name(rawValue
: "DownloadImageNotification")
NotificationCenter.default.post(name
: notificationName
, object
: self,userInfo
: ["value1":"Kody", "value2" : 123])
print("通知完畢")
- 運(yùn)行結(jié)果如下,可以看出,通知發(fā)送后的執(zhí)行是同步的,也就是說觀察者全部處理完畢后,主線程才繼續(xù)往下進(jìn)行:
發(fā)送通知
觀察器
1 獲取到通知,用戶數(shù)據(jù)是[
Kody,123]
觀察器
1 執(zhí)行完畢
觀察器
2 獲取到通知,用戶數(shù)據(jù)是[
Kody,123]
觀察器
2 執(zhí)行完畢
通知完畢
總結(jié)
以上是生活随笔為你收集整理的RxSwift之NotificationCenter的使用和自定义的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。