Memory leak when binding data with rxSwift

When I try to bind mine UITextField

, which is in mine, ViewController

with a variable var location = Variable<String?>("")

that is in mine ViewControllerViewModel

using rxSwift

, I get information about a memory leak. I do it like a roar:

My ViewController

class ViewController {

    @IBOutlet weak var locationTextField: UITextField!
    var viewControllerViewModel: ViewControllerViewModel?
    lazy var disposeBag = DisposeBag()
    /*
        Another variables etc.
    */

    override func viewDidLoad() {
    super.viewDidLoad()

        bindDataWithViewModel()
    }

    func bindDataWithViewModel() {
        if let viewModel = viewControllerViewModel {
            locationTextField.rx.text.bindTo(viewModel.location).disposed(by: disposeBag) -> // here shows memory leak
        }
    }
}

      

My ViewControllerViewModel

class ViewControllerViewModel {

    var location = Variable<String?>("")
    var infoStruct = InfoStruct()
    lazy var disposeBag = DisposeBag()

    init() {
        initValueObservable()
    }

    func initValueObservable() {
        location.asObservable().subscribe(onNext: { [unowned self] text in
        self.infoStruct.location = text
    }).addDisposableTo(disposeBag)
    }
}

      

Do you have any idea why this memory leak is creating itself and how I can avoid it?

+3


source to share


1 answer


func bindDataWithViewModel() {

    if let viewModel = viewControllerViewModel {
        locationTextField.rx.text.orEmpty
            .bindTo(viewModel.location)
            .addDisposableTo(disposeBag) // use addDisposableTo
    }
}

      



0


source







All Articles