androidrx-javarxjs-observablesrx-kotlin

RXKOTLIN/RXJAVA: Communication between the socket using Observables


I am a newbie to RXKotlin/RXJava. I am developing the background service in Android.

In my service, I have

Whenever the data is available on the Bluetooth socket, read and write to the TCP socket. And whenever data is received in the TCP socket, write to the Bluetooth socket.

Can someone help me:


Solution

  • Please try using RxSubjects (https://blog.mindorks.com/understanding-rxjava-subject-publish-replay-behavior-and-async-subject-224d663d452f)

    Let me take PublishSubject as an example here.

    //a publish subject which publishes int values
    public PublishSubject<Integer> source = PublishSubject.create();
    source.onNext(1);
    source.onNext(2);
    

    So above lines of code goes in Bluetooth socket class.

    Now in TCP socket class, using the source, you can observe here.

    source
        .subscribe(
            {
               //result
            },
            {
               //error
            }
        )
    

    Thats it.

    Please make sure, the subscription happens before Bluetooth socket starts publishing data.