Skip to content

Commit

Permalink
ViewModel支持从非主线程中推送数据
Browse files Browse the repository at this point in the history
  • Loading branch information
ITGungnir committed Jan 6, 2020
1 parent 9a28909 commit cb40bd4
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 1 deletion.
7 changes: 7 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -315,6 +315,13 @@ Single.just(ChangeNum(number))
println("------>>${MyRedux.instance.currState().result}")
```

## Change Logs
#### v1.6.4
* ViewModel中支持从非主线程中推送数据

#### v1.6.3
* ViewModel支持传入参数

## License
```text
Copyright 2019 ITGungnir
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package my.itgungnir.rxmvvm.core.mvvm

import android.os.Looper
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.Transformations
import androidx.lifecycle.ViewModel
Expand All @@ -11,7 +12,12 @@ open class BaseViewModel<T : State>(initialState: T) : ViewModel() {
private val state = MutableLiveData<T>().apply { value = initialState }

fun setState(reducer: T.() -> T) {
state.value = reducer(state.value!!)
reducer(state.value!!).apply {
when (Looper.getMainLooper() == Looper.myLooper()) {
true -> state.value = this
else -> state.postValue(this)
}
}
}

fun getState(): T = state.value!!
Expand Down

0 comments on commit cb40bd4

Please sign in to comment.