Skip to content

Commit

Permalink
refactor/#386 ObservablePattern 다중 구독 구현
Browse files Browse the repository at this point in the history
  • Loading branch information
JinUng41 committed Sep 14, 2024
1 parent 482204d commit 75606eb
Showing 1 changed file with 26 additions and 7 deletions.
33 changes: 26 additions & 7 deletions KkuMulKum/Resource/ObservablePattern/ObservablePattern.swift
Original file line number Diff line number Diff line change
Expand Up @@ -10,42 +10,61 @@ import Foundation
class ObservablePattern<T> {
var value: T {
didSet {
listener?(value)
notifyListeners(value)
}
}

private var listener: ((T) -> Void)?
typealias Listener = (T) -> Void

private var listeners: [Listener] = []

init(_ value: T) {
self.value = value
}

private func notifyListeners(_ value: T) {
for listener in listeners {
listener(value)
}
}

func bind(_ listener: @escaping (T) -> Void) {
self.listener = listener
listeners.append(listener)

listener(value)
}

func bind<Object: AnyObject>(with object: Object, _ listener: @escaping (Object, T) -> Void) {
self.listener = { [weak object] value in
listeners.append { [weak object] value in
guard let object else { return }
listener(object, value)
}

listener(object, value)
}

func bindOnMain(_ listener: @escaping (T) -> Void) {
self.listener = { value in
listeners.append { value in
DispatchQueue.main.async {
listener(value)
}
}

DispatchQueue.main.async {
listener(self.value)
}
}

func bindOnMain<Object: AnyObject>(with object: Object, _ listener: @escaping (Object, T) -> Void) {
self.listener = { [weak object] value in
listeners.append { [weak object] value in
guard let object else { return }
DispatchQueue.main.async {
listener(object, value)
}
}

DispatchQueue.main.async {
listener(object, self.value)
}
}
}

0 comments on commit 75606eb

Please sign in to comment.