-
Notifications
You must be signed in to change notification settings - Fork 38
Homework_BasicArchitecture #38
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
AnGuru-60
wants to merge
3
commits into
Android-Developer-Basic:master
Choose a base branch
from
AnGuru-60:master
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or 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
This file contains hidden or 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
140 changes: 140 additions & 0 deletions
140
app/src/main/java/ru/otus/basicarchitecture/AddressFragment.kt
This file contains hidden or 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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,140 @@ | ||
| package ru.otus.basicarchitecture | ||
|
|
||
| import android.os.Bundle | ||
| import android.text.Editable | ||
| import android.text.TextWatcher | ||
| import androidx.fragment.app.Fragment | ||
| import android.view.LayoutInflater | ||
| import android.view.View | ||
| import android.view.ViewGroup | ||
| import android.widget.Toast | ||
| import androidx.fragment.app.viewModels | ||
| import kotlin.getValue | ||
| import ru.otus.basicarchitecture.databinding.FragmentAddressBinding | ||
| import dagger.hilt.android.AndroidEntryPoint | ||
| import android.widget.ArrayAdapter | ||
| import androidx.core.widget.doOnTextChanged | ||
|
|
||
| @AndroidEntryPoint | ||
| class AddressFragment : Fragment() { | ||
| private var _binding: FragmentAddressBinding? = null | ||
| private val binding: FragmentAddressBinding | ||
| get() = _binding ?: throw RuntimeException("FragmentAddressBinding == null") | ||
|
|
||
| private val viewModel: AddressViewModel by viewModels() | ||
| private val adapter by lazy { | ||
| ArrayAdapter( | ||
| requireContext(), | ||
| android.R.layout.simple_dropdown_item_1line, | ||
| mutableListOf<String>() | ||
| ) | ||
| } | ||
|
|
||
| override fun onCreate(savedInstanceState: Bundle?) { | ||
| super.onCreate(savedInstanceState) | ||
| } | ||
|
|
||
| override fun onViewCreated(view: View, savedInstanceState: Bundle?) { | ||
| super.onViewCreated(view, savedInstanceState) | ||
| binding.addressInput.setAdapter(adapter) | ||
| observeViewModel() | ||
| addTextChangedListeners() | ||
| binding.buttonNext.setOnClickListener { | ||
| viewModel.validateData() | ||
| } | ||
|
|
||
| binding.addressInput.setOnItemClickListener { _, _, position, _ -> | ||
| val selectedItem = binding.addressInput.adapter.getItem(position) as? UserAddress | ||
| ?: return@setOnItemClickListener | ||
| selectedItem.let { | ||
| val address = listOf( | ||
| it.country, | ||
| it.city, | ||
| it.street, | ||
| it.house, | ||
| it.block | ||
| ).filter { !it.isBlank() } | ||
| .joinToString(", ") | ||
| binding.addressInput.setText(address) | ||
| } | ||
| } | ||
| } | ||
|
|
||
| override fun onCreateView( | ||
| inflater: LayoutInflater, container: ViewGroup?, | ||
| savedInstanceState: Bundle? | ||
| ): View? { | ||
| _binding = FragmentAddressBinding.inflate(inflater, container, false) | ||
| return binding.root | ||
| } | ||
|
|
||
| fun observeViewModel(){ | ||
| viewModel.errorNetwork.observe(viewLifecycleOwner) { | ||
| if (it) { | ||
| Toast.makeText( | ||
| requireContext(), | ||
| getString(R.string.error_network), | ||
| Toast.LENGTH_SHORT | ||
| ).show() | ||
| } | ||
| } | ||
|
|
||
| viewModel.errAddress.observe(viewLifecycleOwner) { | ||
| with(binding) { | ||
| if (it){ | ||
| addressInput.error = String.format(resources.getString(R.string.empty_field), | ||
| addressInput.hint.toString() | ||
| ) | ||
| } else { | ||
| addressInput.error = null | ||
| } | ||
| } | ||
| } | ||
|
|
||
| viewModel.listUserAddress.observe(viewLifecycleOwner) { listUserAddress -> | ||
| adapter.clear() | ||
| adapter.addAll(listUserAddress.map { | ||
| listOf( | ||
| it.country, | ||
| it.city, | ||
| it.street, | ||
| it.house, | ||
| it.block | ||
| ).filter { !it.isBlank() } | ||
| .joinToString(", ") | ||
| }) | ||
| } | ||
|
|
||
| viewModel.canGoNext.observe(viewLifecycleOwner) { | ||
| if (it){ | ||
| requireActivity().supportFragmentManager.beginTransaction() | ||
| .replace(R.id.mainContainer, InterestsFragment()) | ||
| .commit() | ||
| } | ||
| } | ||
| } | ||
|
|
||
| private fun addTextChangedListeners(){ | ||
| with(binding){ | ||
| addressInput.doOnTextChanged { text, _, _, _ -> | ||
| val address = addressInput.text.toString() | ||
| viewModel.setAddress(address) | ||
| viewModel.searchAddress(address) | ||
| } | ||
| } | ||
| } | ||
|
|
||
| override fun onDestroyView() { | ||
| super.onDestroyView() | ||
| _binding = null | ||
| } | ||
|
|
||
| companion object { | ||
| private const val EXTRA_USER_NAME = "user_name" | ||
|
|
||
| fun newInstance() = AddressFragment() | ||
| } | ||
| } | ||
|
|
||
|
|
||
|
|
64 changes: 64 additions & 0 deletions
64
app/src/main/java/ru/otus/basicarchitecture/AddressVewModel.kt
This file contains hidden or 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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,64 @@ | ||
| package ru.otus.basicarchitecture | ||
|
|
||
| import androidx.lifecycle.LiveData | ||
| import androidx.lifecycle.MutableLiveData | ||
| import androidx.lifecycle.ViewModel | ||
| import androidx.lifecycle.viewModelScope | ||
| import dagger.hilt.android.lifecycle.HiltViewModel | ||
| import kotlinx.coroutines.launch | ||
| import ru.otus.basicarchitecture.address_by_dadata.AddressSuggestUseCase | ||
| import javax.inject.Inject | ||
|
|
||
| @HiltViewModel | ||
| class AddressViewModel @Inject constructor( | ||
| private val cache: WizardCache, | ||
| private val addressSuggestUseCase: AddressSuggestUseCase | ||
| ): ViewModel() { | ||
| private var _listUserAddress = MutableLiveData<List<UserAddress>>() | ||
| val listUserAddress: LiveData<List<UserAddress>> | ||
| get() = _listUserAddress | ||
| private var _canGoNext = MutableLiveData<Boolean>(false) | ||
| val canGoNext: LiveData<Boolean> get() = _canGoNext | ||
| private var _errAddress = MutableLiveData<Boolean>() | ||
| val errAddress: LiveData<Boolean> get() = _errAddress | ||
| private var _errorNetwork = MutableLiveData<Boolean>() | ||
| val errorNetwork: LiveData<Boolean> | ||
| get() = _errorNetwork | ||
|
|
||
| fun validateData() { | ||
| var success = checkEmptyFields() | ||
|
|
||
| if (success == false){ | ||
| _canGoNext.value = false | ||
| return | ||
| } | ||
| _canGoNext.value = true | ||
| } | ||
|
|
||
| fun setAddress(fullAddress: String) { | ||
| cache.userAddress.fullAddress = fullAddress | ||
| } | ||
|
|
||
| fun searchAddress(query: String) { | ||
| viewModelScope.launch { | ||
| try { | ||
| val result = addressSuggestUseCase.invoke(query) | ||
| _listUserAddress.postValue(result) | ||
| } catch (e: Exception) { | ||
| _errorNetwork.postValue(true) | ||
| } | ||
| } | ||
| } | ||
|
|
||
| private fun checkEmptyFields(): Boolean{ | ||
| var success = true | ||
|
|
||
| if (cache.userAddress.fullAddress.isBlank()){ | ||
| _errAddress.value = true | ||
| success = false | ||
| } else{ | ||
| _errAddress.value = false | ||
| } | ||
| return success | ||
| } | ||
| } | ||
51 changes: 51 additions & 0 deletions
51
app/src/main/java/ru/otus/basicarchitecture/Application.kt
This file contains hidden or 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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,51 @@ | ||
| package ru.otus.basicarchitecture | ||
|
|
||
| import android.app.Application | ||
| import dagger.hilt.android.HiltAndroidApp | ||
| import dagger.Module | ||
| import dagger.Provides | ||
| import dagger.hilt.InstallIn | ||
| import dagger.hilt.components.SingletonComponent | ||
| import retrofit2.Retrofit | ||
| import retrofit2.converter.gson.GsonConverterFactory | ||
| import ru.otus.basicarchitecture.address_by_dadata.AddressApiService | ||
| import ru.otus.basicarchitecture.address_by_dadata.AddressCollector | ||
| import ru.otus.basicarchitecture.address_by_dadata.AddressCollectorImpl | ||
| import ru.otus.basicarchitecture.address_by_dadata.AddressSuggestUseCase | ||
| import javax.inject.Singleton | ||
|
|
||
| @HiltAndroidApp | ||
| class HiltApplication : Application() { | ||
|
|
||
| } | ||
|
|
||
| @Module | ||
| @InstallIn(SingletonComponent::class) | ||
| object AppModule { | ||
| @Provides | ||
| @Singleton | ||
| fun provideRetrofit(): Retrofit { | ||
| return Retrofit.Builder() | ||
| .baseUrl("https://suggestions.dadata.ru/suggestions/api/4_1/rs/") | ||
| .addConverterFactory(GsonConverterFactory.create()) | ||
| .build() | ||
| } | ||
|
|
||
| @Provides | ||
| @Singleton | ||
| fun provideDaDataService(retrofit: Retrofit): AddressApiService { | ||
| return retrofit.create(AddressApiService::class.java) | ||
| } | ||
|
|
||
| @Provides | ||
| @Singleton | ||
| fun provideAddressRepository(impl: AddressCollectorImpl): AddressCollector { | ||
| return impl | ||
| } | ||
|
|
||
| @Provides | ||
| @Singleton | ||
| fun provideAddressSuggestUseCase(repository: AddressCollector): AddressSuggestUseCase { | ||
| return AddressSuggestUseCase(repository) | ||
| } | ||
| } |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
@AnGuru-60 , тут все хорошо и правильно. Как вариант, я бы предложил закинуть реактивные свойства (лайвдату или флоу) прямо в визардкеш и проксировать их оттуда через модель. Таким образом, у нас будет один источник истины в данных. Во вьюхе подписываться на них из модели.
Сейчас у нас получается два источника:
Где "истинное" значение данных?
Это может быть потенциальной проблемой, так как у нас несколько мест хранения и состояние не централизовано. Такие штуки описываются концепциями "single source of truth", UDF, MVI и прочим. И композ тоже делить состояние и отображение явно - как раз с этой целью