Last active
March 26, 2019 09:22
-
-
Save ttymsd/962a750d2cc5d9c9f261febe9e4e744f 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
class User | |
class Program | |
class MergedState(u: User, p: Program) | |
interface UserRepository { | |
suspend fun getUser(): User | |
} | |
interface ProgramRepository { | |
suspend fun getPrograms(): List<Program> | |
} | |
fun <X, Y, Z> zip(source1: LiveData<X>, source2: LiveData<Y>, merge: (X, Y) -> Z): LiveData<Z> { | |
return MediatorLiveData<Z>().apply { | |
addSource(source1) { s1 -> | |
val s2 = source2.value | |
if (s1 != null && s2 != null) postValue(merge(s1, s2)) | |
} | |
addSource(source2) { s2 -> | |
val s1 = source1.value | |
if (s1 != null && s2 != null) postValue(merge(s1, s2)) | |
} | |
} | |
} | |
class ActivityScopeViewModel : BaseViewModel() { | |
lateinit var userRepository: UserRepository | |
private val _user = MutableLiveData<User>() | |
val user: LiveData<User> | |
get() = _user | |
fun getUser() { | |
launchWithLoading { | |
_user.postValue(userRepository.getUser()) | |
} | |
} | |
} | |
class FragmentScopeViewModel : BaseViewModel() { | |
lateinit var programRepository: ProgramRepository | |
private val _user = MutableLiveData<User>() | |
private val _programs = MutableLiveData<List<Program>>() | |
val fragmentState: LiveData<List<MergedState>> | |
get() = zip(_user, _programs) { u, p -> | |
p.map { MergedState(u, it) } | |
} | |
fun getPrograms() { | |
launchWithLoading { | |
_programs.postValue(programRepository.getPrograms()) | |
} | |
} | |
fun commitUser(user: User) { | |
_user.postValue(user) | |
} | |
} | |
class DemoActivity : Activity() { | |
lateinit var activityScopeViewModel: ActivityScopeViewModel | |
override fun onCreate(savedInstanceState: Bundle?) { | |
super.onCreate(savedInstanceState) | |
activityScopeViewModel.getUser() | |
} | |
} | |
class DemoFragment : BaseFragment() { | |
lateinit var activityScopeViewModel: ActivityScopeViewModel | |
lateinit var fragmentScopeViewModel: FragmentScopeViewModel | |
override fun onViewCreated(view: View, savedInstanceState: Bundle?) { | |
super.onViewCreated(view, savedInstanceState) | |
activityScopeViewModel.user.observe(this, Observer { | |
fragmentScopeViewModel.commitUser(it) | |
}) | |
fragmentScopeViewModel.fragmentState.observe(this, Observer { | |
// bindingにわたすなり, RecyclerViewの構築を行うなり | |
}) | |
fragmentScopeViewModel.getPrograms() | |
} | |
} |
Author
ttymsd
commented
Mar 26, 2019
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment