3

I have a click event which needs to make a network request.

RxView.clicks(button)
    .flatMapCompletable({ x -> networkCall() })
    .subscribe(...)

The click is an Observable.
networkCall returns a Completable.
However the block inside subscribe is never called when i tap the button.

I've also tried

RxView.clicks(button)
    .flatMap({ x -> networkCall().toObservable<Void>() })
    .subscribe(...)

How can I get this to work so that each time I tap on the button, a network request is made and is then handled in the subscribe.

EDIT:

I haven't done the network stuff yet so currently it's just

public Completable networkCall() {
    Completable.complete();
}

So it's guaranteed to complete.

SunnySydeUp
  • 6,680
  • 4
  • 28
  • 32
  • How do you override subscribe? I am not sure, but if you just override the `onNext` this might not work. Have you also overridden the `onComplete` function with your subscriber? – Christopher Aug 24 '17 at 10:04
  • Regarding the docs, I would also say that flatmapCompletable is not the right option for you: Maps each element of the upstream Observable into CompletableSources, subscribes to them and waits until the upstream and all CompletableSources complete. -> `RxView.clicks` does not complete at all! http://reactivex.io/RxJava/javadoc/io/reactivex/Observable.html#flatMapCompletable-io.reactivex.functions.Function- – Christopher Aug 24 '17 at 10:09
  • @Christopher I had a feeling `flatmapCompletable` wouldn't be appropriate which is why I also tried the second code block. I've overridden `onNext` and `onComplete` and just added logs and breakpoints in those methods and it doesn't hit either. However, even with the second code block, I'm still concerned since it might end the stream when `onComplete` is called from the network call. – SunnySydeUp Aug 24 '17 at 10:17
  • Is my only option to nest the network call inside the subscribe of the click? So basically have two subscriptions? – SunnySydeUp Aug 24 '17 at 10:18
  • @SunnySydeUp, are you sure your networkCall completed? please add the code – yosriz Aug 24 '17 at 10:22

1 Answers1

10

The flatMap case needs items, otherwise its onComplete will never fire due to the already mentioned never-completing clicks source. For example:

RxView.clicks(button)
.flatMap({ x -> networkCall().andThen(Observable.just("irrelevant")) })
.observeOn(AndroidSchedulers.mainThread()) 
.subscribe({ v -> System.out.println(v)}, { e -> e.printStackTrace() })
akarnokd
  • 69,132
  • 14
  • 157
  • 192