4

I have a lambda function that doesn't require any parameter:

Observable.interval(5, TimeUnit.SECONDS)
  .subscribe(x -> new CryptoCompareRxService().getHistoricalDaily("BTC", "USD")
    .subscribe(historicalDaily -> System.out.println("historicalDaily = " + historicalDaily)));

I would like to replace the "x" by "()" because it is useless:

Observable.interval(5, TimeUnit.SECONDS)
  .subscribe(() -> new CryptoCompareRxService().getHistoricalDaily("BTC", "USD")
    .subscribe(historicalDaily -> System.out.println("historicalDaily = " + historicalDaily)));

But when I do that, I get an error:

Cannot infer functional interface type

Why?

Here is the full class:

package com.tests.retrofitrxjava;

import com.tests.retrofitrxjava.rx.CryptoCompareRxService;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import rx.Observable;

import java.util.concurrent.TimeUnit;

@SpringBootApplication
public class RetrofitRxjavaApplication {

  public static void main(String[] args) {

    SpringApplication.run(RetrofitRxjavaApplication.class, args);

    Observable.interval(5, TimeUnit.SECONDS)
      .subscribe(x -> new CryptoCompareRxService().getHistoricalDaily("BTC", "USD")
        .subscribe(historicalDaily -> System.out.println("historicalDaily = " + historicalDaily)));

  }

}
Ori Marko
  • 56,308
  • 23
  • 131
  • 233
Kr1
  • 1,269
  • 2
  • 24
  • 56
  • Java expects a functional interface *with* a parameter because it's going to pass an argument whether you want it or not. Otherwise you're just introducing incorrect semantics for the program - akin to trying to call `((Runnable) r).run(42)` - passing an argument to a method that takes void. Discard parameters (ones you don't use) are a common way of handling that. In many languages, a `_` signifies a discard but [Java is a special case as it doesn't allow it](https://stackoverflow.com/questions/34521690/why-is-a-single-underscore-character-an-illegal-name-for-a-lambda-parameter) – VLAZ Jan 13 '21 at 08:59

1 Answers1

1

I think your mistake is due to change in RX Observable in version 2, where subscribe accept now Consumer which accept parameter

public final Disposable subscribe(Consumer<? super T> onNext)

Consumer<T> A functional interface (callback) that accepts a single value.

and not Action as in version 1

public final Subscription subscribe(Action1<? super T> onNext)

Action1<T> extends Action A one-argument action.

Ori Marko
  • 56,308
  • 23
  • 131
  • 233