I've got a class that does some work and returns t...
# rx
m
I've got a class that does some work and returns the completable. But the work must be sequential and synchronized. So if the work takes 10 seconds to complete and some other entity calls
doWork
during the work being done for the first entity I want it to be queued and wait for it to be finished. At first, I was trying to figure out some clever internal queue based on subject, but failed. Then I thought that simple semaphore will do the job just fine (but also will block the thread). Do you see any problems with such implementations or can it be achieved with similar simplicity with streams without thread blocking?
Copy code
class Foo {

	private val sem = Semaphore(permit = 1)

	fun doWork(): Completable = 
      Completable.fromCallable { sem.acquire() }
        .andThen { doWorkInternal() }
	    .doOnError { sem.release() }
        .doOnComplete { sem.release() }
}
a
Fwiw, I usually solve this problem using a
Subject
. Every time you want to do some "work", you pipe a value through the subject. Then you subscribe to that subject and flatmap to your completable. Natural queuing/ordering ensues.
s
Not related to what you asked, but be careful about calling
andThen
with curly braces instead of parens