0

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

In my service, I have

  • Bluetooth socket
  • TCP Socket

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:

  • how to achieve this using Observables?
  • how to exchange the socket id information?
  • how to exchange the data? Thanks
fab
  • 1,189
  • 12
  • 21
RKVM
  • 67
  • 6

1 Answers1

0

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.

arungiri_10
  • 988
  • 1
  • 11
  • 23
  • Thank you very much. Now its clear about the transferring data from bluetooth class to TCP class. To transfer back another sets of data from TCP class to Bluetooth class, we need create observable in TCP class and observer in Bluetooth class. Is my understanding correct? Thanks – RKVM Jun 14 '21 at 18:14
  • Yes. This approach would work. Also if you think this answer is working for you please accept it. Happy coding – arungiri_10 Jun 15 '21 at 05:32
  • I searched an example using Publishsubject between the class. Could you share one example, if possible. Thank you – RKVM Jun 15 '21 at 12:02
  • It's something similar to livedata usage inside viewmodel and a view. Define subject in one class and access its object from another. – arungiri_10 Jun 17 '21 at 04:34