Tuz
Tuz

Reputation: 1980

Split socket event to multiple handler/subject with rxjs

I have a socket event called "names"

and the data is

data : {
   action : "UPDATE" /"CREATE" /"DELETE"
   payload: {....}
}

now I have 3 subjects and 3 observable and I do smth like:

 switch (){
   case : "UPDATE"
     this.updateSubject.next(val)
   case : "CREATE"
     this.updateSubject.next(val)
  case : "DELETE"
     this.updateSubject.next(val)
  }
    

How can I achieve that in a better way? I tried with FromEvent(socket, 'names')

but I still need 3 subjects and 3 observables

thx

Upvotes: 0

Views: 222

Answers (1)

If i understood right your question you want to handle 3 different response types from a socket with the help of a single subject.

let {
  interval,
  from,
  Subject
} = rxjs
let {
  take,
  concatAll,
  map,
  filter
} = rxjs.operators

 const types = {
  1: 'UPDATE',
  2: 'DELETE',
  3: 'CREATE'
 }


let ref = document.querySelector('#container')

/** Socket part*/
const _subject = new Subject();

const update$ = _subject.pipe(filter(x => x === 'UPDATE'), map(() => 'Update Handler'))
const delete$ = _subject.pipe(filter(x => x === 'DELETE'), map(() => 'Delete Handler'))
const create$ = _subject.pipe(filter(x => x === 'CREATE'), map(() => 'Create Handler'))

const socket$ = interval(1000).pipe( map(() => {
 const type = Math.ceil(Math.random()*3)
 return types[type]
}));
socket$.subscribe(x => _subject.next(x))

/** Handlers */

delete$.subscribe(x => console.log(x))
create$.subscribe(x => console.log(x))
<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/6.5.5/rxjs.umd.js"></script>

<div id="container"></div>

With this implementation you have a single Subject and three observables (which are all consuming the same source), and from this point on you can trigger handlers wherever you want.

I wouldn't say that my solution is better, as both yours and mine will work the same way, but in my version i've used more reactive/functional approach. The benefits of this approach is that you can scale-up the socket functionality in an easier to reason manner.

Upvotes: 1

Related Questions