Is there a Java equivalent to C#'s 'yield' keyword?

前端 未结 6 1111
自闭症患者
自闭症患者 2020-11-27 11:36

I know there is no direct equivalent in Java itself, but perhaps a third party?

It is really convenient. Currently I\'d like to implement an iterator that yields all

6条回答
  •  死守一世寂寞
    2020-11-27 12:17

    I'd also suggest if you're already using RXJava in your project to use an Observable as a "yielder". It can be used in a similar fashion if you make your own Observable.

    public class Example extends Observable {
    
        public static void main(String[] args) {
            new Example().blockingSubscribe(System.out::println); // "a", "b", "c", "d"
        }
    
        @Override
        protected void subscribeActual(Observer observer) {
            observer.onNext("a"); // yield
            observer.onNext("b"); // yield
            observer.onNext("c"); // yield
            observer.onNext("d"); // yield
            observer.onComplete(); // finish
        }
    }
    

    Observables can be transformed into iterators so you can even use them in more traditional for loops. Also RXJava gives you really powerful tools, but if you only need something simple then maybe this would be an overkill.

提交回复
热议问题