如何在单独的线程中监听HashMap值的变化使其成为Flowable?

时间:2017-10-05 08:02:54

标签: android rx-java rx-java2

我有想要听取变化的项目的地图并做出一些动作 我想在单独的线程中完成它,但地图已更改,但我可以听取它的更改

val removedItemList: HashMap<Int,Item> = HashMap()

Flowable.fromArray(removedShoppingList.values).subscribeOn(Schedulers.io())
    .observeOn(AndroidSchedulers.mainThread())
    .subscribe({ items ->
      Log.i("items_removed", " " + items + items.size);
    })

1 个答案:

答案 0 :(得分:1)

请尝试以下代码:

// When HashMap changed, this class emitted.
class MapEvent(val event: EventType, val item: Item?){
    enum class EventType {
        ADD,
        REMOVE
    }
}

~~~

// PublishSubject emits changed event.
val subject = PublishSubject.create<MapEvent>()

// Subscribe changed event.
// When emits changed event by PublishSubject, print log.
val obervable = subject.hide().share()
obervable.subscribeOn(Schedulers.io())
        .observeOn(AndroidSchedulers.mainThread())
        .subscribe {it -> Log.i("HashMap Changed", "Event: ${it.event}, Item: ${it.item}")}

val itemList: HashMap<Int, Item> = HashMap()
val addedItem = Item()

// If you add or remove HashMap item, then execute onNext method in order to emit changed event.
itemList.put(1, addedItem)
subject.onNext(MapEvent(MapEvent.EventType.ADD, addedItem))
val removedItem = itemList.remove(1)
subject.onNext(MapEvent(MapEvent.EventType.REMOVE, removedItem))