Home > AI > IOS > Combine >

PassthroughSubject

API

Example 1:

struct Article: Codable {
    let title: String
    let author: String
    let pubDate: Date
}

// publisher
let publisher = PassthroughSubject<Data, Never>()


// subscriber
let cancellable = publisher
    .decode(type: Article.self, decoder: JSONDecoder())
    .sink(receiveCompletion: { print ("Completion: \($0)")},
          receiveValue: { print ("value: \($0)") })


publisher.send(Data("{\"pubDate\":1574273638.575666, \"title\" : \"My First Article\", \"author\" : \"Gita Kumar\" }".utf8))

Example 2:

var pub = PassthroughSubject<String, Never>()
pub.sink(receiveCompletion: {
    print("Received completion \($0)")
}, receiveValue: { value in
    print("Received value \(value)")
})

pub.send("Hello")
pub.send("World")
pub.send(completion: .finished)
pub.send("good")

Example 3:

extension Notification.Name {
    static let myName = Notification.Name("myName")
}

let pub = PassthroughSubject<Notification, Never>()
NotificationCenter.default.addObserver(forName: .myName, object: nil, queue: nil) { note in
  pub.send(note)
}
pub.sink(receiveValue: { note in
  print("received notification: \(note)")
})
NotificationCenter.default.post(name: .myName, object: nil, userInfo: ["Hello": "World!"])

Example 4:

import SwiftUI
import Combine


struct ContentView: View {
    @ObservedObject var demo1 = DemoOneViewModel()
    @ObservedObject var demo2 = DemoTwoViewModel()
    
    
    var body: some View {
        VStack {
            Text("\(demo1.a), \(demo1.b), \(demo1.c), \(demo1.d)")
                .onTapGesture {
                    demo1.change()
                }
            
            Text("\(demo2.a), \(demo2.b), \(demo2.c), \(demo2.d)")
                .onTapGesture {
                    demo2.change()
                }
        }
        
    }
}


class DemoOneViewModel: ObservableObject {
    // this whole class get changed, needless to declare @Published, to save energy
    let objectWillChange = PassthroughSubject<DemoOneViewModel, Never>()
    
    var a: Int = 0
    var b: Int = 1
    var c: Int = 2
    var d: Int = 3
    
    func change() {
        a += 1
        b += 1
        c += 1
        d += 1
        objectWillChange.send(self)
    }
    
}

// same effect
class DemoTwoViewModel: ObservableObject {
    
    @Published var a: Int = 0
    @Published var b: Int = 1
    @Published var c: Int = 2
    @Published var d: Int = 3
    
    func change() {
        a += 1
        b += 1
        c += 1
        d += 1
    }
    
}

Leave a Reply