第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

觀察變量的變化

觀察變量的變化

牧羊人nacy 2021-04-01 13:11:03
我有一個在多個地方(一個用戶)使用的變量。我不想每次打開片段或活動時獲得該信息,而減少網(wǎng)絡(luò)流量。我正在考慮的是一次獲取此數(shù)據(jù),然后在其他地方進行觀察。我了解有諸如Observable和Eventbuses之類的東西,我研究了RxJava2,但似乎找不到找到更新Observable所持有價值的方法。你能告訴我我應(yīng)該怎么做嗎?我還想看看是否有一種方法可以每隔一段時間(例如,每1秒鐘)重新更新一次數(shù)據(jù)。
查看完整描述

2 回答

?
慕尼黑的夜晚無繁華

TA貢獻1864條經(jīng)驗 獲得超6個贊

您可以按以下方式處理:


您可以在一個Repository類中從網(wǎng)絡(luò)中獲取數(shù)據(jù),并使該類成為單例。然后從服務(wù)中檢索數(shù)據(jù)并將其發(fā)送到LiveData對象?,F(xiàn)在,您可以觀察到該LiveData對象以及從服務(wù)中分別檢索數(shù)據(jù)的方法。因此,一旦檢索到數(shù)據(jù),便可以將其用于將來使用;如果要再次從服務(wù)中檢索數(shù)據(jù),則可以調(diào)用檢索方法并進行觀察。


類似于以下代碼:


(注意:此代碼僅是示例,由于我不了解您的模型,因此沒有必要進行編譯。)


 DataRepository {


    private static DataRepository instance;

    private final LiveData<User> userLiveData;


    private DataRepository() {}


    public synchronized static DataRepository getInstance(){

        synchronized (DataRepository.class) {

           if(instance == null){

               instance = new DataRepository();

               instance.userLiveData = new MutableLiveData();

           }

        }

        return instance;

    }


    public LiveData<User> getUser(){             

         return userLiveData;

    }


    public LiveData<User> fetchUser(){

         callGetUserServiceAsync();

         return userLiveData;

    }


    public void callGetUserServiceAsync(){

        //call your service asynchronously and when service call back is called do as below, this call sample is in retrofit format, yours might be different

        callService().enqueue( new CallBack<User>(){


               @Override

               public void onResponse(Call<IndraConfigure> call, Response<IndraConfigure> response) {

                    userLiveData.postValue(response.body); //assuming that response.body is of type User

                }


                @Override

                public void onFailure(Call<IndraConfigure> call, Throwable t) {

                    // do something relevant when call fails to fetch user

                }

            );

        } 

    }


 }

然后,當(dāng)您想從服務(wù)中檢索用戶時,在代碼中(最好是使用MVVM的ViewModel),請執(zhí)行以下操作:


 DataRepository.getInstance().fetchUser().observe() {

  ....

 }

當(dāng)您只想使用以前獲取的數(shù)據(jù)時,請執(zhí)行以下操作:


DataRepository.getInstance().getUser().observe() {

 ....

}

請注意,您必須fetchUser()至少調(diào)用一次該方法,然后才能通過調(diào)用獲得用戶數(shù)據(jù)getUser()。


查看完整回答
反對 回復(fù) 2021-04-14
?
料青山看我應(yīng)如是

TA貢獻1772條經(jīng)驗 獲得超8個贊

我認(rèn)為您應(yīng)該考慮將其LiveData與MVVM體系結(jié)構(gòu)一起使用。


TL; 博士

簡而言之,您將要做的是這樣的事情:


SharedSessionViewModel


public class SessionSharedViewModel extends ViewModel {



    private LiveData<Session> sharedSession = new MutableLiveData()


    public SessionSharedViewModel() {

        super();

    }


    public void setSession(Session data) {

        MutableLiveData<Session> casted = (MutableLiveData<Session>) this.sharedSession

        casted.postValue(data)

    }

    public LiveData<Session> getSharedSession() {

        return this.sharedSession;

    }

}

第一片段


public class FirstFragment extends Fragment() {



    private SessionSharedViewModel session;


    // some sort of callback called when the user session arrives from the API

    public void methodThatHandlesUserData(Session user){

        session.getSharedSession().setSession(user);

    }

    public void onActivityCreated(Bundle savedInstanceState) {

        super.onActivityCreated(savedInstanceState)

        session = ViewModelProviders.of(this.activity).get(SessionSharedViewModel.class)

        session.sharedSession.observe({yourobservablehere});

        Observer<Session> userObserver = new Observer<>(){

            @Override

            public void onChanged(Session user){observableCallback(user);}

        };

        sharedViewModel.sharedSession.observe(userObserver);

    }

    public void observableCallback(newSession: Session) {

        // Do something when returning to this fragment

    }

}

詳細(xì)片段


class SessionDetailsFragment : Fragment() {


    private SessionSharedViewModel sharedViewModel;


    public void onActivityCreated(Bundle savedInstanceState) {

        super.onActivityCreated(savedInstanceState)

        sharedViewModel = ViewModelProviders.of(this.activity).get(SessionSharedViewModel.class)

        Observer<Session> userObserver = new Observer<>(){

            @Override

            public void onChanged(Session user){observableCallback(user);}

        };

        sharedViewModel.sharedSession.observe(userObserver);

    }


    public void observableCallback(newSession: Session) {

        Toast.makeText(activity, "This is inside new activity: "+newSession.getUsername(), Toast.LENGTH_SHORT);

    }

}

進一步閱讀

LiveData已被Android團隊采用,它由的新androidx庫完全支持,構(gòu)成的一部分Android Arquitechture Components

使用LiveData提供了一組不錯的良好功能,例如:

  • 沒有內(nèi)存泄漏

  • 您的應(yīng)用的用戶界面與數(shù)據(jù)狀態(tài)相符

  • LiveData知道生命周期,因此不會再因Activity生命周期(ViewModel<3 LiveData)而崩潰

  • 在活動和片段之間共享資源的能力

為了進一步閱讀,我建議您去這里


查看完整回答
反對 回復(fù) 2021-04-14
  • 2 回答
  • 0 關(guān)注
  • 198 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動學(xué)習(xí)伙伴

公眾號

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號