I'm trying to make chat services chain with RxSwift. Basically it should do:
Basically function below works, but it is not checking socket connection status for now. It should check before second flatMap if sockets are connected, if yes it should go to flatMap with messageUpload if not it should wait until connection returns true. I have Variable with is telling me about current connection status(Bool)
chatSocketService.isSubscribedToChannel.asObservable()
but I can't figure out how to put them together. I tried with third flatMap(before current last one) it doesn't work. Next problem is that user can try to send few messages before connection is back so each time he hits sendButton this method is executed, so it should send only last message when connection is back. Any idea how I can handle that with Rx?
func sendMessage(withBody body: String) {
guard !body.isEmpty else { return }
Observable.just(chatModel.value)
.filter({ $0.product != nil })
.flatMap({ [unowned self] chatModel -> Observable<ChatModel> in
if chatModel.id != nil {
return Observable.just(chatModel)
} else {
return self.createChat(withProductModel: chatModel.product!)
}
})
.flatMap({ [unowned self] chatModel -> Observable<ChatMessageModel> in
return self.chatService.uploadChatMessage(forChat: chatModel, withBody: body)
.trackActivity(self.progressHelper.activityIndicator)
})
.subscribe(onNext: { [unowned self] chatMessageModel in
self.finishedSendingMessage.onNext(())
})
.addDisposableTo(disposeBag)
}
.flatMap({ [unowned self] chatModel -> Observable<ChatMessageModel> in
let successfulConnect = chatSocketService.isSubscribedToChannel.asObservable()
.skipWhile { $0 == false }
.map { _ -> Void in }
.take(1)
return successfulConnect.flatMap { self.chatService.uploadChatMessage(forChat: chatModel, withBody: body) }
.trackActivity(self.progressHelper.activityIndicator)
})
The above code should have the behavior described in the question for managing the connection. successfulConnect
is an observable that will emit a value and complete when the connection status is true.
skipWhile
will ignore false
values, map
transforms our observable from Observable<Bool>
to Observable<Void>
and take(1)
makes sure the observable completes after the first value. flatMap
then performs uploadChatMessage
when sucessfulConnect
sends a value.
The second behavior you describe implies cancelling the previous upload if user sends another message before the previous one has been uploaded. This can be handled by disposing of the subscription on entering sendMessage
var disposable: Disposable?
func sendMessage(withBody body: String) {
disposable?.dispose()
disposable = Observable.just(chatModel.value)
// ...
.subscribe(onNext: { /* ... */ })
}
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments