RxJava Tutorial on RxJava BehaviorSubject

behaviorsubject emits the most recent item it has observed and then all subsequent observed items to each subscribed observer.

class declaration

following is the declaration for io.reactivex.subjects.behaviorsubject<t> class −

public final class behaviorsubject<t>
extends subject<t>

behaviorsubject example

create the following java program using any editor of your choice in, say, c:\> rxjava.

observabletester.java

import io.reactivex.subjects.behaviorsubject;
public class observabletester  {
   public static void main(string[] args) {   
      final stringbuilder result1 = new stringbuilder();
      final stringbuilder result2 = new stringbuilder();         
      behaviorsubject<string> subject =  behaviorsubject.create(); 
      subject.subscribe(value -> result1.append(value) ); 
      subject.onnext("a"); 
      subject.onnext("b"); 
      subject.onnext("c"); 
      subject.subscribe(value -> result2.append(value)); 
      subject.onnext("d"); 
      subject.oncomplete();
      //output will be abcd
      system.out.println(result1);
      //output will be cd being behaviorsubject 
      //(c is last item emitted before subscribe)
      system.out.println(result2);
   }
}

verify the result

compile the class using javac compiler as follows −

c:\rxjava>javac observabletester.java

now run the observabletester as follows −

c:\rxjava>java observabletester

it should produce the following output −

abcd
cd