The .sink block inside the ViewModel class is called automatically when launching the controller a second time

I have a SwiftUI view embedded inside Controller A using UIHostingController. Controller A is launched from Controller B. The SwiftUI view uses a ViewModel class. In the ViewModel, I have subscribed to some publishers and I want to send data to Controller A.

//This is the ViewModel file that contains a publisher to receive the video URL upon capture, and I am sending this URL to a controller using PassthroughSubject.

class GenericCameraViewViewModel: ObservableObject {
    let xCamSession: XCamSession
    
    var preview: some View {
        xCamSession.interactivePreview()
    }
    
    private var subscription = Set<AnyCancellable>()
    
    public var cameraEventSubject = PassthroughSubject<GenericCameraResult, Never>()
    
    
    init(genericCameraConfiguration: GenericCameraConfiguation) {

        // Prepare video album cover
        xCamSession.videoFilePublisher
            .receive(on: DispatchQueue.main)
            .map {result -> URL? in
                if case .success(let file) = result {
                    return file.path
                } else {
                    return nil
                }
            }
            .sink(receiveValue: { fileURL in
                debugPrint("Receive file url")
                self.cameraEventSubject.send(GenericCameraResult(event: .capturedVideo, images: nil, videoFile: fileURL))
//                if self.shouldSendData {
//                    self.xCamSession.terminateSession({ result in
//                        self.cameraEventSubject.send(GenericCameraResult(event: .capturedVideo, images: nil, videoFile: fileURL))
//                        debugPrint("Receive file url")
//                        
//                    })
//                }
                
            })
            .store(in: &subscription)
        
        }
}
// a function in the controller to add SwiftUI view and subscribe the subject
    
    // display the measure view as a view controller child
    private func addAsAChild(){
        
        //let config = GenericCameraConfiguation(captureMode: .photo,canCaputreMultiplePhotos: true, cameraPosition: .back,cameraPhotoFlash: .off,cameraVideoTorch: .auto)
        
        let viewModel = GenericCameraViewViewModel(genericCameraConfiguration: configuration)
        let videoContentView = GenericCameraView(viewModel: viewModel)
        viewModel.cameraEventSubject
        .receive(on: DispatchQueue.main) // Ensure sink runs on main thread
        .sink(
            receiveCompletion: { completion in
                print("-- completion", completion)
                self.cancellables.first?.cancel()
                self.dismiss(animated: true)
                
            },
            receiveValue: {[weak self] result in
                viewModel.shouldSendData = false
                switch(result.event){
                case .closePressed:
                    viewModel.cameraEventSubject.send(completion: .finished)
                    debugPrint("Close Button Pressed")
                    break
                case .donePressed:
                    debugPrint("Done Button Pressed  (result.images ?? [])")
                    viewModel.cameraEventSubject.send(completion: .finished)
                    let capturedImages = result.images ?? []
                    let arrImagePaths = self?.saveImages(images: capturedImages)
                    self?.mDelegate?.capturedImagesPath(capturedImages: arrImagePaths ?? [])
                    break;
                case .capturedPhoto:
                    debugPrint("capturedPhoto Button Pressed  (result.images ?? [])")
                    let capturedImages = result.images ?? []
                    let arrImagePaths = self?.saveImages(images: capturedImages)
                    self?.mDelegate?.capturedImagesPath(capturedImages: arrImagePaths ?? [])
                    
                case .capturedVideo:
                    debugPrint("capturedVideo Button Pressed  (result.videoFile ??  URL.init(string: "https://cameraxaapp.com")!)")
                    self?.mDelegate?.capturedVideoUrl(videoUrl: result.videoFile)
                    //viewModel.cameraEventSubject.send(completion: .finished)
                }
            }
        ).store(in: &cancellables)
        
        let hostingViewController = HostingController(rootView: videoContentView)
        addChildWithView(hostingViewController)
    }

To achieve this, I added a PassthroughSubject inside the ViewModel and subscribed to this subject inside Controller A. I am sending data using this subject within the publisher’s .sink method, and it works fine. However, when I open Controller A again, the .sink method of the publisher is called automatically.

New contributor

Vishal Bhargava is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật