I'm trying to implement RxSwift
single observable:
class Doctor {
var disposeBag = DisposeBag()
func sanityCheck() -> Single<String> {
return Single<String>.create {[weak self] observer in
if self?.amICrazy() == true {
observer(.success("Yes, you are crazy"))
}else {
observer(.error(someError.notCrazy))
}
return Disposables.create()
}
}
func amICrazy() -> Bool {
return arc4random_uniform(2) == 0
}
}
But the problem the self
is always nil.
Any of you knows why self
is nil or how can fix it?
I'll really appreciate your help.
You using weak
capture for self
in creation closure for Single
, so unless you hold strong reference on your Doctor
object, it will be deallocated as soon as you leave allocation context.
BTW, in latest swift you can use Bool.random()
to get random boolean value.
func amICrazy() -> Bool {
return Bool.random() // or just .random()
}