Android RxJava how to check if an object is on the list

289 Views Asked by At

I have this code:

var kitchenList: MutableList<Dish> = ArrayList()
var intervalObser = interval(1, TimeUnit.SECONDS)
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())

        
        intervalObser.subscribe({
            fromIterable(orderList)
                .filter { it.status.equals("to create")
                }
                .subscribe({
                    kitchenList.add(it)
                    Log.d("add", "success")
                },{Log.d("add", "error")})
        },{})

where he finds meals to be done and adds them to the list in the kitchen every second but how to check if the data about a specific id is already on the kitchenList using rxJava? And how to stop adding 10 dishes and restart adding after removing one or more.

Is there any other method responsible for the repetition than the interval used above?

1

There are 1 best solutions below

1
On

You could do something like this (although it is a bit convoluted for producing the required behavior):

val orderList: MutableList<Dish> = ArrayList()
val kitchenList: MutableList<Dish> = ArrayList()

fun setCreated(id: Int) : Unit {
    Observable.fromIterable(orderList)
    .filter { it.id == id }
    .doOnNext { it.status = "created" }
    .subscribe()

    Observable.fromIterable(kitchenList)
    .filter { it.id != id }
    .toList()
    .doOnSuccess { 
        kitchenList.clear()
        kitchenList.addAll(it)
    }
    .subscribe()
 
    updateKitchen()
}
fun updateKitchen() : Unit {
    Observable.fromIterable(orderList)
    .filter { it.status == "to create" }
    .flatMapMaybe { outer ->
         Observable.fromIterable(kitchenList)
         .any { it.id == outer.id }
         .filter { !it }
         .map { outer }
    }
    .takeWhile { kitchenList.size < 10 }
    .doOnNext { kitchenList.add(it) }
    .subscribe()
}