xskit
xskit

Reputation: 431

Handling activity initialization

I have an Activity and inside this activity, I have some initialization code:

private fun init() {
        val authorFullName = photo?.user?.name ?: "?"
        val source = getString(R.string.unknown)

        photoAuthorText.text = String.format(getString(R.string.photo_by_s_on_s), authorFullName, source)

        Utils.makeUnderlineBold(photoAuthorText, arrayOf(authorFullName, source))
    }



 private fun loadPhoto() {
        Glide.with(this)
                .asBitmap()
                .load(photo?.urls?.regular)
                .into(object : SimpleTarget<Bitmap>() {
                    override fun onResourceReady(resource: Bitmap, transition: Transition<in Bitmap>?) {
                        photoImageView.setImageBitmap(resource)
                    }
                })
    }

Then inside onCreate I simply call:

init()
loadPhoto()

My question is do I need to move this logic from those two initialization methods to ViewModel? I don't think that to keep that logic in Activity is a good idea.

I know about DataBinding but I don't want to use it. Are there any other approaches?

Upvotes: 0

Views: 52

Answers (1)

Rajesh
Rajesh

Reputation: 732

Check in Java

Activity Code public class UserProfileActivity extends Activity { UserProfileModel viewModel;

 @Override
 protected void onCreate(Bundle savedInstanceState) {
     super.onCreate(savedInstanceState);
     setContentView(R.layout.user_activity_layout);
     viewModel = ViewModelProviders.of(this).get(UserProfileModel.class);
     bindData();        

 }

void bindData() {
    viewModel.userLiveData.observer(this, new Observer() {
        @Override
         public void onChanged(@Nullable UserFullDetails data) {
             // update ui.
             // You can set Profile Image And User Details UI Components
         }
     });
}

}

This ViewModel Code

public class UserProfileModel extends ViewModel {
     private MediatorLiveData<UserFullDetails> userFullDetails;
     public UserModel() {

     }

     public LiveData<UserFullDetails> getUserFullDetails() {
        if (userFullDetails == null) {
            userFullDetails = new MediatorLiveData<>();
            getUpdatedUserData();
        }
        return userFullDetails;
    }

    void getUpdatedUserData() {
        LocalData<UserFullDetails> mResponse = getDataFromDataSource(); //Data come from local or cloud
        userFullDetails.setValue(mResponse.getData());
    }
 }

Upvotes: 1

Related Questions