Search code examples
swiftreactive-programmingrx-swiftmoya

RxSwift/Moya - Sequence won't start if it is returned via function


I try to start a network request via Moya.

    let provider = MoyaProvider<User>()

    provider.rx.request(.Auth(username: username, password: password))
        .filterSuccessfulStatusAndRedirectCodes()
        .debug()
        .mapOptional(to: Authentication.self)
        .observeOn(MainScheduler.instance)
        .subscribe {
            event in
            print(event)
        }.disposed(by: disposeBag)

When I do it the above way everything works fine.

But if I do it this way:

func logIn(username: username, password: password) -> Single<Authentication?> {

    let provider = MoyaProvider<User>()

    return provider.rx.request(.Auth(username: username, password: password))
        .filterSuccessfulStatusAndRedirectCodes()
        .debug()
        .mapOptional(to: Authentication.self) 
}

And then calling the function:

self.loginIn(username: username, password: password)
        .observeOn(MainScheduler.instance)
        .subscribe {
            event in
            print(event)
        }
        .disposed(by: disposeBag)

The debug output states that it get subscribed, but it won't start the sequence if i return it via the function.


Solution

  • I have solved the error. You need to retain the provider. Store it in an instance variable and it will not be disposed.

    https://github.com/Moya/Moya/issues/1460