Skip to content

Commit

Permalink
Merge pull request #387 from OMZigak/refactor/#386-observablePattern
Browse files Browse the repository at this point in the history
[refactor] ObservablePattern 다중 구독 구현하기
  • Loading branch information
JinUng41 authored Sep 15, 2024
2 parents 482204d + dc1ce1f commit 913bfcb
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 8 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)
}
}
}

Original file line number Diff line number Diff line change
Expand Up @@ -26,4 +26,3 @@ protocol PromiseServiceProtocol {
func deletePromise(promiseID: Int) async throws -> ResponseBodyDTO<EmptyModel>?
func exitPromise(promiseID: Int) async throws -> ResponseBodyDTO<EmptyModel>?
}

0 comments on commit 913bfcb

Please sign in to comment.