Last active
November 4, 2018 17:47
-
-
Save myeonginwoo/2df2572d62672ddd3b9a5cf440594bb5 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// before | |
class MainViewModel(val view: MainView, val dataStore: DataStore) { | |
private var currentItem: Item by Delegates.observable(Item("kotlin", "#FF0000"), | |
{ _: KProperty<*>, oldItem: Item, newItem: Item -> | |
view.onUpdatedItem(oldItem, newItem) | |
}) | |
private var currentState: NetworkState<Item> by Delegates.observable(NetworkState.Init(), | |
{ _: KProperty<*>, _: NetworkState<Item>, newState: NetworkState<Item> -> | |
when (newState) { | |
is NetworkState.Init -> view.hideProgress() | |
is NetworkState.Loading -> view.showProgress() | |
is NetworkState.Success<Item> -> currentItem = newState.item | |
is NetworkState.Error -> view.onError(newState.throwable) | |
} | |
}) | |
fun requestItemInfo(itemType: ItemType) { | |
currentState = NetworkState.Init() | |
currentState = try { | |
NetworkState.Success(dataStore.getItemInfo(itemType)) | |
} catch (error: Throwable) { | |
NetworkState.Error(error) | |
} finally { | |
currentState = NetworkState.Init() | |
} | |
} | |
} | |
// after | |
class MainViewModel(val view: MainView, val dataStore: DataStore) { | |
private val compositeDisposable: CompositeDisposable by lazy { CompositeDisposable() } | |
private var currentItem: Item by Delegates.observable(Item("kotlin", "#FF0000"), | |
{ _: KProperty<*>, oldItem: Item, newItem: Item -> | |
view.onUpdatedItem(oldItem, newItem) | |
}) | |
private var currentState: NetworkState<Item> by Delegates.observable(NetworkState.Init(), | |
{ _: KProperty<*>, _: NetworkState<Item>, newState: NetworkState<Item> -> | |
when (newState) { | |
is NetworkState.Init -> view.hideProgress() | |
is NetworkState.Loading -> view.showProgress() | |
is NetworkState.Success<Item> -> currentItem = newState.item | |
is NetworkState.Error -> view.onError(newState.throwable) | |
} | |
}) | |
fun requestItemInfo(itemType: ItemType) { | |
dataStore.getItemInfo(itemType) | |
.observeOn(AndroidSchedulers.mainThread()) | |
.doOnSubscribe { currentState = NetworkState.Loading() } | |
.doOnTerminate { currentState = NetworkState.Init() } | |
.subscribe({ | |
currentState = NetworkState.Success(it) | |
}, { | |
currentState = NetworkState.Error(it) | |
}) | |
.also { | |
compositeDisposable.add(it) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment